From what I know, if you create a global struct as follows:
something name;
int main(){
}
You are able to access every field of the struct something, but if I were to instead make it as:
something* name;
int main(){
}
Would this now be incorrect because I have to malloc the size of the struct?
Note, I haven't decided what the struct something contains, this is more of a general question.
CodePudding user response:
Basically, pointer is just a variable that points to some address in memory. So after
something* name;
int main(){
}
all you have is a pointer. It should point to a place in memory, where struct
something exists, but for now its just garbage there (notice that pointer can point to random location and as long as you don't try to do something with it no error will occur). After calling malloc system will reserve space needed for something and return pointer you should assign to global variable.
CodePudding user response:
Would this now be incorrect because I have to malloc the size of the struct?
Well, it depends on how you are going to use it.
Code like:
something* name;
int main(){
}
is by it self perfectly valid C code.
You can for instance use it like:
something* name;
int main(){
something x = {....};
name = &x; // Make name point to a "something" object
...
name->some_member = ...;
...
}
or like
something* name;
int main(){
something x = {....};
name = malloc(sizeof *name); // Make name point to a "something" object
assert(name != NULL);
...
name->some_member = ...;
...
}
But without an assignment to name like name = ... you can't dereference the pointer. In other words, this would be invalid
something* name;
int main(){
...
name->some_member = ...; // INVALID
...
}
because name doesn't point to a "something" object.
BTW:
Since name is global the code
something* name;
is the same as
something* name = NULL;
UNRELATED:
There are cases where global variables are good and useful but in most cases, it's best to avoid globals.
