How is the array stored in memory?

I have a simple program that initializes an array as:

int a[]={10,20,30,40,50};

char *p;

p=(char*)a;

Now I want to access the value in each byte using a pointer p. To do this, I need to know how the array is stored in memory (stack or heap)?

+5
source share
4 answers

.
, . , .
:
, , , . , , .

  • () ,
  • () bss/data​​strong >
  • .
+19

, :

, , , , .

, , :

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

.

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

. , , :

 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]);
+6

.data/.bss . ( new malloc) .

+1

First, the pointer must be of type int. An array is just a whole group stored in memory as one, but on one line. An integer has 4 bytes in memory, so you can access each value in your array by increasing your pointer by 4.

int *p = (int*)a;
for(i = 0; i < 5; i++) {
    p += 4;
    printf("%d ", *p);
}
-3
source

All Articles