Karthick
Karthick

Reputation: 1000

Initializing pointers during declaration in c

How does the following work?

char *str="string";
printf("str is %s\n",str);

but the below one gives segmentation fault

int *i=3;
printf("int is %d\n",*i);

Upvotes: 2

Views: 87

Answers (2)

juanchopanza
juanchopanza

Reputation: 227390

A string literal such as "string" is a char[7] stored in a read-only memory location. Array names can decay to pointers to their first element, so it is possible to initialize a char* to such a literal expression.

An integer literal such as 3 is just an int rvalue which is not stored anywhere. The initialization int* i = 3 initializes i to point to a memory location with value 3. This is unlikely to be a valid location, which is why de-referencing i gives you a segmentation violation.

Upvotes: 7

haccks
haccks

Reputation: 106012

In case of string literals, compiler allocate space for it in memory. str will be initializes with the starting address of the allocated chunk.
In case of int *i=3;, compiler initializes i with the address value 3. Generally lower addresses are reserved for operating systems and programs will most likely crash on accessing these location

Upvotes: 3

Related Questions