why this code give error

Mar 10, 2017 at 9:58am
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);
}
Mar 10, 2017 at 10:07am
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.
Mar 10, 2017 at 1:33pm
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 Mar 10, 2017 at 1:43pm
Mar 11, 2017 at 6:24am
thanks @integralfx and @Peter87 for clarification.
Another solution is :
ptr = malloc(4);
then
*ptr = *(arr + 2) ;
Mar 11, 2017 at 7:13am

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.
Mar 12, 2017 at 8:24pm
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.