1

As part of a larger project, I am trying to write a function that will allocate enough memory for a struct variable and assign values to its member variables after scanning them from the keyboard. In other words, I am trying to create a sort of a constructor function. The reason for this is because I think that's the best way to create a database-like program in c, where all the student_t variables will be stored in a student_t* array called classroom.

#include <stdio.h>
#include <stdlib.h>
#define N 10
#define STRLIM 50

typedef struct student{
char* name;
int age;
}student_t;


student_t* init_student(student_t* s);

int i=0;//its the array counter
student_t* classroom[N];

int main(int argc, char const *argv[]){

while(i<N){
  //  classroom[i]=(student*)malloc(sizeof(student));
    init_student(classroom[i]);
    classroom[i]->age=i;
    printf("The age of student #%d is : %d \n",i,classroom[i]->age);
    printf("the name of student #%d is : %s",i,classroom[i]->name);
    i++;
}

    printf("the size of the classroom is : %ld",sizeof(classroom));
    return 0;
}//end of main()

student_t* init_student(student_t* s){
    s=(student_t*)malloc(sizeof(student_t));
    s->name=(char*)malloc(sizeof(char)*STRLIM);
    fflush(stdin);
    fgets(s->name,STRLIM,stdin);

    return s;
}

Gdb ouput shown in the attached image here.

Please check out my repo. I am guessing something about my build and datatypes is off .Thanks in advance.

7
  • Beware, POSIX considers typedefs ending in _t to be standard, and student_t definitely isn't. I see no reason to unnecessarily typedef this struct anyway. As for the issue at hand, I think s=(student_t*)malloc(sizeof(student_t)); will change the local variable only. You might need to use student_t ** as the parameter. Commented Mar 22, 2021 at 13:20
  • what is the question? Commented Mar 22, 2021 at 13:21
  • 1
    Or use the returned value: classroom[i] = init_student(); Commented Mar 22, 2021 at 13:22
  • 1
    I'd recommend to keep object allocation and user input separated. Commented Mar 22, 2021 at 14:25
  • 1
    you were all pretty much right and your suggestions really helped me especially @mediocrevegetable1. After all of that, I figured out that I was worried about the wrong thing since the very first moment and my code had a much bigger problem. If you are reading this , don't malloc and return, it's just asking for trouble! read this Commented Mar 23, 2021 at 16:46

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.