The following C program is not supposed to work by my understanding of pointers but it does.
#include<stdio.h>
main() {
char *p;
p = "abcdefghijk";
printf("%s", p);
}
Outputs:
abcdefghijk
The char pointer variable p
is pointing to something random as I have not assigned any address to it like p = &i;
where i
is some char array.
That means if I try to write anything to the memory address held by the pointer p
it should give me segmentation fault since it is some random address not assigned to my program by the OS.
But the program compiles and runs successfully. What is happening?
In C a string literal like "abcdefghijk"
is actually stored as an (read-only) array of characters. The assignment makes p
point to the first character of that array.
I note that you mention p = &i
where i
would be an array. That is in most cases wrong. Arrays naturally decays to pointers to their first element. I.e. doing p = i
would be equal to p = &i[0]
.
While both &i
and &i[0]
would result in the same address, it is semantically very different. Lets take an example:
char array[10];
With the above definition doing &array[0]
(or just plain array
as explained just above) you get a pointer to char
, i.e. char *
. When doing &array
you get a pointer to an array of ten characters, i.e. char (*)[10]
. The two types are very different.