If I allocate memory for a char a[256], initialise each element to a different value and pass this to some function:
int subFunc(a);
how does the stack frame of subFunc look?
Does the stack frame contain all the 256 bytes in it or just a pointer to the address of a (4 bytes).
If a pointer, then how does it access the data inside the subFunc or where is this data available to subFunc?
subFuncwill receive a pointer tochar, not an array ofchar. The details of how that pointer is passed will vary with the implementation. The pointer value may be pushed onto the stack, or it may be passed in a register (gcc 2.96 on Red Hat does the former, while gcc 4.1.2 on SLES 10 does the latter), and that may depend on things like optimization settings, whether you’re generating a debug version, etc. The only way to know for sure how it works on your platform is to code it up, build it, and look at the generated machine code.In most circumstances, an expression of type “N-element array of
T” will be converted (“decay”) to an expression of type “pointer toT“, and the value of the expression will be the address of the first element of the array. The exceptions to this rule are when the array expression is an operand of thesizeof,_Alignof, or unary&operators, or is a string literal being used to initialize the contents of another array in a declaration.Given the code
the expression
ain the call tosubFunchas type “256-element array ofchar“; by the rule above, it is replaced with an expression of type “pointer tochar” (char *) and its value is the address ofa[0].Thus,
subFuncreceives a pointer value, not an array ofchar.Note that, in the context of a function parameter declaration,
T a[]andT a[N]are interpreted asT *a; if your prototype forsubFuncisit will be interpreted as