raghu wrote:
su*******@rediffmail.com wrote: Hi all,
recently i tried the following peice of code in gcc
int main ()
{
char *ptr = "possible";
printf("%s",ptr);
return (0);
}
the output was :
possible
now how was this done? i did not assign memory to ptr ! please
explain...
sumit
I think the question sumit is asking is.........
usually pointer points to the address of a variable i.e int i =9; int
*ptr; ptr=&i(here we assigned the address); printf("%d",*ptr); gives
output : 9
In the same way in the sumit program we hav not at all assigned the
pointer the address of a variable,then how come the output is "
possible".
even i have a doubt in this.pls help
Why do you think it is not assigned an address? Where do you think the
string "possible" is stored.. on paper? Of course the string "possible"
is stored somewhere in memory. Exactly where depends on OS, CPU,
compiler etc.. etc... But when you type:
char *ptr = "possible";
The pointer ptr is pointing to where the string possible is stored
(actually where the first byte is stored). What's so hard to
understand.
A few things to note. String literals are read-only (don't remember the
correct C term). You are not supposed to write to a string literal. So:
x = *ptr;
y = ptr[3];
are legal, but:
*ptr = 'X';
ptr[3] = 'Y';
are not legal.
The second thing to remember is that although ptr points to where the
string "possible" is stored it is a regualr char pointer and may point
to anything else. But when you do this, remember to have something else
point to the string literal or you'll never be able to point anything
to it ever again. For example:
char *ptr = "possible";
ptr = some_other_byte_array;
/* at this point, nothing can point to the string "possible" */