I think my answer is great for you,you may misunderstand the definition of the pointer and use the pointer in a wrong way. Let`s analyse your code first:
int *p = 10
this statement defines a pointer which is pointed to address 10 in memory, it compiles OK because there's no syntax error--the content of p is the address 10, but you have no idea what's value in address 10, and it generally doesn't have a internal memory to store a value cuz you haven`t allocate the memory for it.it's also very dangerous that you are tring to use a system memory 10.
You can print the address which has been pointed by p:
printf("%d\n", p);//p is pointed to address 10
So when you tried to print the content of p by:
printf("\n%d",*p);
which haven't allocate the memory to store the content,segmentation fault occurs!
If u want to assign value for pointer directly u must dynamic application of memory space for it first, you should write in this way:
int *p = NULL;//the right and safe habit to define a pointer
p = (int *)malloc (sizeof(int));//dynamic application of memory space of pointer p to store value
if (NULL == p)
{
printf("malloc failed!\n");//show error
exit(1);//exit
}
*p = 10;//now you have memory space to store value 10
printf("%d\n", *p);
free(p);//release the memory to avoid memory leaks
p = NULL;//the right and safe habit
You can also write in this way:
int transfer_value = 10;//integer has memory when you declare it
int *p = &transfer_value;//p stores the address of i which content is value 10
printf("%d\n", *p);//because variable i has memory which size is sizeof(int), you can print *p(it stands for the value of i)directly.
Hope my explanation could help you ^_^
p
. – molbdnilo Feb 16 '16 at 9:21char* c = "abc";
, wherec
is a pointer to the first element of an array that may be stored in read-only memory, but the value ofc
isn't stored in read-only memory in that case either. – molbdnilo Feb 16 '16 at 9:32-std=c11 -pedantic-errors
, otherwise it won't behave as a standard C compiler. In your case, the compiler is also so old that it doesn't even support C11, meaning you have to use-std=c99
. – Lundin Feb 16 '16 at 9:34