我正在努力解决结构指针及其在函数中的使用问题。这里,我有个问题。下面的代码没有打印我想要打印的ID、姓名和分数。我花了好几个小时想弄明白。谁能用通俗易懂的方式解释一下吗?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct examinee
{
char ID[8];
char name[32];
int score;
};
struct examinee* init(char ID[8], char name[32], int score){
struct examinee* instance;
instance = (struct examinee*)malloc(sizeof(struct examinee));
strcpy(instance->ID, ID);
strcpy(instance->name, name);
instance->score;
return instance;
};
int main(int argc, char *argv[])
{
struct examinee examinee_1;
struct examinee* examinee_1_ptr = init("IO760","Abe",75);
examinee_1_ptr= &examinee_1;
printf("examinee's information:nID: %snname: %snscore: %dn", examinee_1_ptr->ID, examinee_1_ptr->name, examinee_1_ptr->score);
return 0;
}
本行
struct examinee* examinee_1_ptr = init("IO760","Abe",75);
执行该函数并将结果存储在examinee_1_ptr
变量中。
然后这两行
struct examinee examinee_1;
examinee_1_ptr= &examinee_1;
创建一个空的examinee
实例,并用该空实例的地址覆盖指针。在这一点上,你在init()
中创建的一个丢失了,因为没有任何东西指向它的地址,所以你没有办法访问它。去掉这两行,你就没事了。
printf("examinee's information:nID: %snname: %snscore: %dn", examinee_1_ptr->ID, examinee_1_ptr->name, examinee_1_ptr->score);
注意,这里您只能通过指针访问对象。一开始就不需要examinee_1
变量。