Just a simple struct called person, inside I need to store name and age. I'm trying to dynamically allocate memory for my struct.
Without using pointer:
#include <stdio.h>
#include <stdlib.h>
typedef struct person
{
char name[10];
int age;
} person;
int main(int argc, char *argv[])
{
person a = {"bob", 15}; // Here, we can input values "together", all at once
printf("name is %s, age is %i\n", a.name, a.age);
return 0;
}
Here, it can successfully print out:
name is bob, age is 15
Using pointer:
int main(int argc, char *argv[])
{
person *a = (person *) malloc(sizeof(person));
if (a == NULL)
return 1;
*a = {"bob", 15}; // Here I tried to input the all values
printf("name is %s, age is %i\n", a->name, a->age);
free(a);
return 0;
}
It won't compile and return the error:
expected expression before '{' token
Well, if I try to input the value one by one:
int main(int argc, char *argv[])
{
person *a = (person *) malloc(sizeof(person));
if (a == NULL)
return 1;
a->name = "bob";
a->age = 15;
printf("name is %s, age is %i\n", a->name, a->age);
free(a);
return 0;
}
it can successfully print out:
name is bob, age is 15
I expected that since the pointer is pointing to memory allocated to be a struct person, values can be input together just like a normal struct. But as you can see, it couldn't. However, when values were input one by one, it worked.
Did I do sth wrong? Or when using pointers, I need to input the value one by one? Thank you.
You likely want a compound literal.
And don't cast the return from malloc
.
int main(void)
{
person *a = malloc(sizeof(person));
*a = (person){"bob", 15}; // Here I tried to input the all values
printf("name is %s, age is %i\n", a->name, a->age);
free(a);
return 0;
}
You also should get in the habit of checking to ensure that malloc
succeeded before using that memory.