-
It’s known that big local/global variables may cause to a stack overflow.
I know that using pointers and allocating space in memory helps to overcome this problem.
But is it the only option? What happens if I have (or need) too-many pointers in global scope? -
Regarding the stack space: Is a global struct-type variable takes space in the stack, or acts like a pointer? Do I need to create a pointer of a struct variable type in order to reduce the stack load?
-
Does the following code allocates memory also to the char** variable named
BIG?// in the header file typedef struct myStruct { BIG[256][256]; int baz; } myStruct; // in the c file myStruct* foo; foo = (myStruct*) malloc( sizeof(*foo) ); -
How can I easily cast the return value of
malloc()? In question #3 I wrote:foo = (myStruct*) malloc( sizeof(*foo) );But I prefer to write something like:
foo = (foo) malloc( sizeof(*foo) ); // the compiler reports an errorWhich will ease the pain when editing the code (when changing the type of
foo).
English isn’t my native language so sorry for any lack of clarity.
Neil already answered your questions, here are my comments on your 3rd and 4th questions.
(I fixed the error in
BIG‘s type.) This will allocate space forBIG, althoughBIGis not of typechar **.BIGis of type “array [256] of array [256] ofchar“. In value contexts, it is equivalent to “pointer to array [256] ofchar“.You’re almost correct in what you want to do, but the right way requires even less typing! The most idiomatic, easy to read, and “type-change safe” way is:
Or more generally,
No casts are needed, since
malloc()returnsvoid *, which can be converted to any pointer type back and forth without any loss of information. Note that this form does not use the type offooin themalloc()call, so it is type-agnostic. Also,sizeofoperator doesn’t need parentheses if it’s used on an object (but they’re needed if it’s used on a type).