David Edgar David Edgar - 1 year ago 71
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
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{

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

int status = 0;

Student john

/* Function call to allocate memory*/

status = initMemory(&john);


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 */


Answer Source

Just replace

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


(*_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 !

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download