Reputation: 107
I want to be create a struct, but I also want to write its array or string elements with dynamic memory allocation.
struct st {
char *name[40];
int age;
};
For "name" string should I use malloc before struct, or can I use it in struct also.
1)
char *name = malloc(sizeof(char)*40);
struct st {
char *name;
int age;
};
2)
struct st {
char *name = malloc(sizeof(char)*40);
int age;
};
Are both of them true or is there any mistake? And if both of them are true, which one is more useful for other parts of code?
Upvotes: 0
Views: 2201
Reputation: 66
Declaring a type does not create lvalues (like variable). It defines the format of the lvalue. In 1), you have correctly declared a struct type, but you seem to have assumed the similarity of the "name" variable in struct declaration will associate the pointer "name" to struct member "name". It does not work that way.
2) is syntactically/symantically wrong. You simply cannot assign a malloc() to non-lvalue (as you are declaring a type struct)
So, create a variable out of struct type as you have created in 1) and allocate memory in the struct variable member.
typedef struct st {
char *name;
int age;
} st_type;
st_type st_var;
st_var.name = (char *) malloc(sizeof(char) * 40); // This is how you will allocate the memory for the struct variable.
Remember, before you can do dynamic allocation, you need to have a lvalue just like you did for standalone "name" variable.
Upvotes: 1
Reputation: 409166
You need to create an instance of the structure, an actual variable of it. Then you need to initialize the members of the structure instance in a function.
For example, in some function you could do
struct st instance;
instance.name = malloc(...); // Or use strdup if you have a string ready
instance.age = ...;
Upvotes: 2
Reputation: 1621
An option would be to have a pointer in the struct however allocate memory outside of the struct within the function you use it.
e.g.
struct st {
char* n;
int a;
};
void foo() {
char* name = malloc(sizeof(char) * 40);
int age = 0;
struct st s = (struct st) {
.n = name,
.a = age,
};
/* TO DO */
free(name);
}
Upvotes: 1