-5
#include<stdio.h>

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

    p=(char*)a;
    for(i=0;i<8;i++)
    {
        printf("%d    %u\n",*p,p);
        p++;
    }
    return 0;
}

Please explain the behavior that how array is stored in memory?

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
som
  • 481
  • 1
  • 4
  • 9
  • Based on this and a [previous question](http://stackoverflow.com/questions/10696024/how-is-the-array-stored-in-memory), you should find a [good C book](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list). – Blastfurnace May 31 '12 at 06:12
  • Sequentially allocated block of memory, when it's array of integers it will allocate 4 bytes for each element or depending on the system, google it dude, SOF is not for that kind of questions. – Ahmed Jolani May 31 '12 at 06:13
  • Strictly speaking, `p=(char*)a;` is undefined behavior. The code will be dependent on endianess. – Lundin May 31 '12 at 06:59

1 Answers1

2

Your array is stored in one continuous block of memory:

index:      0       |       1       |      2       |      3        |      4
bytes: 0  1  2  3   |  4  5  6  7   |  8  9 10 11  |  12 13 14 15  | 16 17 18 19
values:    10       |      20       |      30      |     40        |      50

These questions will help you:
Address of first element in static declaration of array
How does this pointer arithmetic work?

Community
  • 1
  • 1
LihO
  • 41,190
  • 11
  • 99
  • 167