Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between arrays and pointers in c? [duplicate]

Tags:

arrays

c

pointers

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;
}
like image 897
A.s. Bhullar Avatar asked Jun 13 '26 15:06

A.s. Bhullar


2 Answers

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.

like image 191
Vijay Avatar answered Jun 15 '26 07:06

Vijay


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.

like image 39
LZR Avatar answered Jun 15 '26 07:06

LZR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!