应该 return 结构指针的函数
Function that should return structure pointer
我正在研究结构指针及其在函数中的用法。在这里,我有一个问题。下面的代码没有打印我希望它打印的 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: %s\nname: %s\nscore: %d\n", 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: %s\nname: %s\nscore: %d\n", examinee_1_ptr->ID, examinee_1_ptr->name, examinee_1_ptr->score);
注意这里你只是通过指针访问对象。首先不需要 examinee_1
变量。
我正在研究结构指针及其在函数中的用法。在这里,我有一个问题。下面的代码没有打印我希望它打印的 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: %s\nname: %s\nscore: %d\n", 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: %s\nname: %s\nscore: %d\n", examinee_1_ptr->ID, examinee_1_ptr->name, examinee_1_ptr->score);
注意这里你只是通过指针访问对象。首先不需要 examinee_1
变量。