I am writing a compiler for a "c-like" language. Currently, the compiler supports arrays in local scope. Each element of an array may be accessed using bracket notation—a[0], a[1],.... to support this data structure, a symbol table is used to keep track of the symbols in the current scope, and the address of the next available memory space. to demonstrate, consider the following code:
int a[5]; int b;
using a stack implementation, and given a 4 byte aligned memory: in order to access, e.g. element a[1], I calculate the memory location by
element = ((index+1) * 4) + a.Address; // a.Address is the address of a, which is stored in the symbol table, and index is 1 in this case.
so, the symbol table doesn’t store the address of each individual element of ‘a’, only the address of the symbol and, for each symbol, the next memory address.
I am assuming that the c language uses a stack based implementation for arrays in local scope, such as what I’ve done. However, how does the C language pass a local array as a parameter to a function, like the following?
foo(int[] a) {}
Would a C compiler use the heap or the stack to pass the foregoing array?
In C, arrays decay to pointers when passed as function arguments;
foo(int a[])is identical tofoo(int * a), and only the pointer to the first element “survives” into the function call. There is no way to recover the array size from the pointer within the function call.