3

I am really confused in arrays and pointers.
Please tell me What is difference between following two codes?

int main()
{
    int i,*p;
    for(i=0;i<5;i++)
    {
        p[i]=i;
        printf("%d",p[i]);
    }
return 0;
}

int main()
{
    int i,p[5];
    for(i=0;i<5;i++)
    {
        p[i]=i;
        printf("%d",p[i]);
    }
return 0;
}
Suraj Jain
  • 4,463
  • 28
  • 39
A.s. Bhullar
  • 2,680
  • 2
  • 26
  • 32
  • 1
    @devnull What's it got to do with fairness? It's just desirable - if you don't see it happening it's probably because the other viewers don't have a good answer bookmarked, or one's harder to find... just start it off with your own close vote.... – Tony Delroy Jul 05 '13 at 12:31
  • I was pretty sure it's a duplicate when I saw the title, then hesitated at its description, yet there *must be* similar posts lying around with the same root cause. Yet I realize that it may be hard for a novice user to relate them to his problem. Therefore I don't vote down for this. – phoeagon Jul 05 '13 at 12:35
  • Hey plz tell me about flags and votes... – A.s. Bhullar Jul 05 '13 at 12:46

2 Answers2

7

First one results in undefined behaviour. For not having UB you need to allocate memory using either malloc or calloc. Allocating memory will store the data in heap. After you done with your task , you need to free the allocated memory also.

Second one do not result in UB. it stores the array data in stack and not on heap. Memory is automatically freed from stack once the scope is over.

Vijay
  • 65,327
  • 90
  • 227
  • 319
  • Thanks a lot @Vijay actually i am new to c can you please tell me where can i find more information about how data is stored in heap or stack? – A.s. Bhullar Jul 05 '13 at 12:50
4

In first p points to garbage location (not-allocated), and I'm pretty sure that in the way you are using it will generate a segmentation fault. You should allocate memory first, before using it, like:

p = malloc(5 * sizeof(int))

Second is allocated on stack and have the lifetime of the scope it is declared in.

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
LZR
  • 948
  • 10
  • 28
  • Not necessarily segmentation fault, its undefined behaviour, his code may run, or may be crash with core dump. its undefined read Vijay's answer. – Grijesh Chauhan Jul 05 '13 at 12:42
  • thanks @Pavel.lazar and Grijesh Chauhan can u please tell me more about segmentation fault? – A.s. Bhullar Jul 05 '13 at 12:53
  • @A.s.Bhullar why not read this: [Segmentation fault](http://en.wikipedia.org/wiki/Segmentation_fault) ,read OS sends a signal to process and kill – Grijesh Chauhan Jul 05 '13 at 13:01