Why are the memory addresses ascending in one place and descending in another?

arrays, c

Solution

It's a detail of the compiler, and the architecture, what order a-e are in. Those variables are on the stack, which on most (but not all) architectures grows downwards -- that is, the innermost function will have local variables with the lowest addresses, and the functions which called that function will have local variables with higher addresses. In a situation like that (where all the variables are declared in the same function, and particularly in the same scope), the compiler gets to choose what it will put where, and it looks like your compiler has chosen to order them downwards in order of declaration.

In contrast, within an array, the memory locations of elements are pretty much guaranteed to be in ascending order of index. (IIRC, technically this is allowed to not be the case, but I don't know of any compilers that sadistic.)

Problem

Here is a simple C program I wrote: ``` int main(void) { char str[]="abcde"; int len = strlen(str); for(int i=0;i<len;i++) printf("%c : %p\n",str[i], (void*) &str[i]); int a,b,c,d,e=10; printf("The memory address of a is: %p\n", (void*) &a); printf("The memory address of b is: %p\n", (void*) &b); printf("The memory address of c is: %p\n", (void*) &c); printf("The memory address of d is: %p\n", (void*) &d); printf("The memory address of e is: %p\n", (void*) &e); return 0; } ``` It gives the following output: ``` a : 0x7fff59e358a6 b : 0x7fff59e358a7 c : 0x7fff59e358a8 d : 0x7fff59e358a9 e : 0x7fff59e358aa The memory address of a is: 0x7fff59e35898 The memory address of b is: 0x7fff59e35894 The memory address of c is: 0x7fff59e35890 The memory address of d is: 0x7fff59e3588c The memory address of e is: 0x7fff59e35888 ``` Why are memory addresses increasing for the `char` array and decreasing for the `int`s?

Original source