结构体数组初始化

来源:百度知道 编辑:UC知道 时间:2024/06/02 16:31:51
#include <stdio.h>
#include <malloc.h>

struct Info {
char name;
};
void main()
{
int i;
struct Info *data = malloc(5*sizeof(struct Info));
char namex[3];
for (i=0; i<5;i++)
{
sprintf(namex, "%d", i);
data[i].name = namex;
}
printf("%s\n", data[1].name);
free(data);
}
输出的结果是4 怎样输出结果才能是1啊
为什么输出不是1呢?
我想要的就是结构题数组赋值,怎么办才能在FOR中赋值呢?

1. namex是一个字符数组,不是单个字符。
2. C语言中,字符数组是不能直接当右值用“=”号赋值,应该使用strcpy,strncpy,memcpy等函数进行赋值。
添加改过的程序

#include <stdio.h>
#include <string.h>
#include <malloc.h>

struct Info {
char name[3];
};
void main()
{
int i;
char namex[3] = "";

struct Info *data = malloc(5*sizeof(struct Info));
memset(data, 0, 5*sizeof(struct Info));

for (i=0; i<5;i++)
{
sprintf(namex, "%d", i);
strcpy(data[i].name, namex);
}
printf("%s\n", data[1].name);
free(data);
}

你这个程序有严重的缓冲区溢出呀,因为循环到4就停止,所以就输出4呀,如果你想输出1可以这样

#include <stdio.h>
#include <malloc.h>

struct Info {
char name;
};
void main()
{
int i;
struct Info *data = malloc(5*sizeof(struct Info));
char namex[3];
for (i=0; i<2;i++)
{
sprintf(namex, "%