I have a quick question about the syntax and the code.
I just found out a way to declare the struct in C which is a bit different from what I\'ve seen so far.
Th
Generally speaking, you can't "assign values to a pointer". A pointer only stores a single value, which is the address of an already existing object.
If you have a pointer pointing to an existing struct variable, you can just initialize that:
struct student s = { .name = "Max", .age = 15, .grade = 8 };
struct student *p = &s;
If you want to use dynamic memory allocation, things get a bit tricker:
struct student *p = malloc(sizeof *p);
if (!p) {
...
}
malloc
gives you uninitialized memory, and you cannot use initializer syntax with existing objects.
But you can use a trick involving compound literals (available since C99):
*p = (struct student){ .name = "Max", .age = 15, .grade = 8 };
Here we use a compound literal to create a new unnamed struct object whose contents we then copy into *p
.
The same feature can be used to get rid of s
in the first example:
struct student *p = &(struct student){ .name = "Max", .age = 15, .grade = 8 };
But in this version p
still points to automatic memory (like a local variable).