Home > Blockchain >  return a struct pointer from a function with return type char*
return a struct pointer from a function with return type char*

Time:08-15

I have to create a function that, given a student ID, will look through an array of pointers to struct members(students) and return a char pointer to that student. the function should return null if no student is found.

the function prototype below was provided by the professor and cannot be changed, the find id function is correct I believe but I don't know how I'm suppose to return the pointer to the student if the return type is char* and the student type is struct. if someone can point me in the right direction(no pun intended) id appreciate it.

char * find_id(int id, struct student * arr[], int n)

struct definition

struct student {
  int id;
  char * name;
};

create student function

struct student * create_student(int id, char * name){
  struct student *ptr = (struct student*) malloc( sizeof(struct student));
      if(ptr==NULL){
         return NULL;
       }
  ptr->id = id;
  ptr->name = malloc((strlen(name) 1)* sizeof(char));
      if(ptr->name == NULL){
         free(ptr);
         return NULL;
       }
  strcpy(ptr->name, name);
  return ptr;
}

my find_id function

char * find_id(int id, struct student * arr[], int n){
    
    for(int i = 0; i<n;i  ){
        if(arr[i]->id == id){
            return arr[i];

        }
        else{
            return NULL;
        }
    }
    
}

Main function

int main(){
char name1[]="ALI";
char name2[]="MOE";
char name3[]="AYA";
char name4[]="RANA";
char name5[]="BOB";
int id1 = 10000;
int id2 = 10001;
int id3 = 10002;
int id4 = 10003;
int id5 = 10004;

struct student *student[4];
student[0] = create_student(id1,name1);
student[1] = create_student(id2,name2);
student[2] = create_student(id3,name3);
student[3] = create_student(id4,name4);
student[4] = create_student(id5,name5);

for(int i=0; i<5;i  ){
  free_student(student[i]);
}
assert(strcmp(find_id(10000,student,5),"ALI")==0);
}

CodePudding user response:

You can't return a struct student * from a function which has a return type of char *.

As such, the professor probably asked to return the name of the student, not the student structure itself.

CodePudding user response:

  1. By this part:

    if(arr[i]->id == id) { return arr[i]; }

Your implementation of find_id() doesn't return char * but struct student *;

  1. By this part:

    else { return NULL; }

Your implementation of find_id() doesn't iterate the whole array, but return always at the first member of the array;

The find function should be like this:

char *find_id(int id, struct student *arr[], int n) {
    char *retval = NULL;
    for(int i = 0; i < n; i  ){
        struct student *p = arr[i];
        if(p->id == id)
        {
            retval = p->name;
            break;
        }
    }
    return retval;
}
  •  Tags:  
  • c
  • Related