Home > other >  Function that should return structure pointer
Function that should return structure pointer

Time:05-17

I am grappling with structure pointers and their usage in functions. Here, I have a problem. The code below isn't printing the ID, name, and score which I would like it to print. I spent hours trying to figure this out. Can anyone please explain it in an easy-to-understand way?

#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;
}

CodePudding user response:

In this line

struct examinee* examinee_1_ptr = init("IO760","Abe",75);

you execute the function and store the result in the examinee_1_ptr variable.

But then these two lines

struct examinee examinee_1; 
examinee_1_ptr= &examinee_1;

create an empty examinee instance and override the pointer with the address of that blank instance. At this point, the one you created in init() is lost, because nothing is pointing at its address anymore so you have no way to access it. Remove those two lines and you'll be fine.

printf("examinee's information:\nID: %s\nname: %s\nscore: %d\n", examinee_1_ptr->ID, examinee_1_ptr->name, examinee_1_ptr->score);

Note that here you are only accessing the object through the pointer. There is no need to have the examinee_1 variable in the first place.

  • Related