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;
}
3
  • 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.... Commented Jul 5, 2013 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. Commented Jul 5, 2013 at 12:35
  • Hey plz tell me about flags and votes... Commented Jul 5, 2013 at 12:46

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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?
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.

3 Comments

Not necessarily segmentation fault, its undefined behaviour, his code may run, or may be crash with core dump. its undefined read Vijay's answer.
thanks @Pavel.lazar and Grijesh Chauhan can u please tell me more about segmentation fault?
@A.s.Bhullar why not read this: Segmentation fault ,read OS sends a signal to process and kill

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.