你这里似乎有很多问题。首先,您选择在结构中创建Name
和ID
指针。这意味着您需要在开始使用它们之前为两者动态分配内存:
struct data data1;
data1.ID = malloc(sizeof(int));
data1.Name = malloc(50); // so arbitrary amount big enough for a name.
我不确定你为什么选择创建ID
一个指针,它不一定在这个例子中,如果不是,它可能更容易理解;所以考虑改变它。
现在scanf()
需要一个格式字符串和许多指向正在读取的每种类型的指针。在您的情况下,您只是在读取一个 int 和一个字符串,所以您拥有的是:
scanf("%d",data1.ID);
scanf("%s",data1.Name);
很好,请记住,如果您选择更改ID
为 aint
而不是指针,则需要传递它的地址:scanf("%s",&data1.ID);
printf()
接受一个格式字符串,以及要打印的格式的数据。在你的情况下:
printf("The new ID is \n",&data1.ID); // you're giving the address of the int
printf("The name input is \n",&data1.Name); // and the address of the string
但是您没有提供任何格式...并且您不想发送指针的地址,这没有意义。
printf("The new ID is %d\n",*data1.ID); // %d for an int, and * to dereference
printf("The name input is %s\n",data1.Name); // %s for a string
您想要做的是相应地使用int%d
和%s
字符串(就像 with 一样scanf()
),但是由于ID
是指针,因此您需要在将其传递给printf()
. C 中没有“字符串”类型,所以当你告诉printf()
期待一个字符串时,它只需要一个char *
已经data1.Name
存在的字符串。