why this code give error

Error: Segmentation fautlt

1
2
3
4
5
6
7
8
9
10
  #include <stdio.h>

void main()
{
int arr[5] = {1,2,3,4,5};
int *ptr ;
*ptr = *(arr + 2);
//ptr ++ ; 
printf("VAlue = %d\n",*ptr);
}
int *ptr ;
ptr is uninitalised which means it contains some garbage value.

*ptr = *(arr + 2);
Dereferencing a garbage value will lead to undefined behaviour, usually program crashing. You're trying to access memory that you don't have permission to, resulting in a segmentation fault.
If you want ptr to point to the third element in the array you should have written
 
ptr = arr + 2;
or
 
ptr = &arr[2];
Last edited on
thanks @integralfx and @Peter87 for clarification.
Another solution is :
ptr = malloc(4);
then
*ptr = *(arr + 2) ;

Another solution is :
ptr = malloc(4);
then
*ptr = *(arr + 2) ;

I thought you were using ptr, to access arr's elements? If so, there is no need to dynamically allocate memory. You can just assign ptr to arr.
If you want to store a copy of the array element, why not simply store it in a regular int variable?
Topic archived. No new replies allowed.