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;
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With