Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the array stored in memory?

I have a simple program which initializes an array as:

int a[]={10,20,30,40,50};   
char *p;
p=(char*)a;

Now I want to access the value at each byte through pointer p. For that I need to know: how is the array stored in memory? Is it stored on the stack or the heap?

like image 878
som Avatar asked May 22 '12 05:05

som


People also ask

How are arrays stored in memory Javascript?

In Javascript, an array is a Hashtable Object type so the interpreter doesn't need to keep track of physical memory and changing the value of an element doesn't affect other elements as they're not stored in a contiguous block of memory.

How are arrays stored in memory python?

1) Array. Python has a built-in module named 'array' which is similar to arrays in C or C++. In this container, the data is stored in a contiguous block of memory. Just like arrays in C or C++, these arrays only support one data type at a time, therefore it's not heterogenous like Python lists.


2 Answers

An array stores its elements in contiguous memory locations.
If You created the array locally it will be on stack. Where the elements are stored depends on the storage specification.
For Example:
An array declared globally or statically would have different storage specification from an array declared locally. Technically, the where part is implementation defined but usually implementations would use similar usage patterns.

  • A local array will be (usually) created on stack while
  • A global or static array will be (usually) created on bss/data segments and
  • A dynamically created array will be created on heap.
like image 183
Alok Save Avatar answered Sep 21 '22 19:09

Alok Save


Since I can't add comments just yet, here's my two cents in an answer:

If you only want to know if the memory is on the stack or heap, read the other answers, they are much more informed than me.

If you want to know exactly where the values are, you can always print the address:

printf("address at a[0] = %p\n", (void *)&a[0]);
printf("address at p[0] = %p\n", (void *)&p[0]);

where you will notice the same answer. But, then look at

printf("address at a[1] = %p\n", (void *)&a[1]);
printf("address at p[1] = %p\n", (void *)&p[1]);

Which is a fun little exercise. Just for fun, run the following code and see what you get:

 p[2] = 'a';
 printf("a[0] is %d\n", a[0]);
 printf("a[1] is %d\n", a[1]);
 printf("p[2] is %d\n", p[2]);
 putchar(p[2]);
like image 30
NickO Avatar answered Sep 19 '22 19:09

NickO