David Edgar David Edgar - 21 days ago 6
C Question

Allocate memory for char array pointer of struct inside function

I was looking around for about one day on how to solve my problem. I find solutions for problems similar to mine but when I apply changes error :

error: request for member 'mark' in something not a structure or union
keeps showing.

What I have so far is a
struct
and I want to initialize it on a function call.

Edit my code:

typedef struct student * Student;

struct student {
char *mark; /* or array[2] like array[0] = 'A' , array[1] = 'B' */
int age;
int weight;
};

typedef enum{
MEMORY_GOOD,
MEMORY_BAD} Status;

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

int status = 0;

Student john


/* Function call to allocate memory*/

status = initMemory(&john);

return(0);
}


Status initMemory(Student *_st){
_st = malloc(sizeof(Student));


printf("Storage size for student : %d \n", sizeof(_st));

if(_st == NULL)
{
return MEMORY_BAD;
}

_st->mark = malloc(2*sizeof(char)); /* error: request for member 'mark' in something not a structure or union */

return MEMORY_GOOD;
}

Answer

Just replace

_st->mark = malloc(2 * sizeof(char));

With

(*_st)->mark = malloc(2 * sizeof(char));

_st is a pointer wich content is the address of the struct, so ...

1) first you need to dereference _st, and...
2) second, with the value you get, you point to the field mark

That's all !