Link to home
Start Free TrialLog in
Avatar of srinivas_vemla
srinivas_vemla

asked on

pointer does not get assigned...

Hi,

I do:

char str[10]="abcd";
char *sptr = str;

sptr[2]='p';

This works...


But

char *sptr = "abcd";
printf("%s\n", sptr[2]);   //This works

sptr[2] = 'p';

This does not work...

I don't get the difference between these 2... they both are pointers and are pointing to a string...

can someone throw some light on this....

Thanks
SOLUTION
Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of srinivas_vemla
srinivas_vemla

ASKER

Thanks jaime,

Yeah, that was a typo on the printf() line...

So, do you mean that since I assigned sptr to "abcd", I cannot change a single character in it again?... But how come I can change if I declare the string like:

char s[] = "abcd";
s[2] = 'p';  //This works
 
I don't get the difference clearly...
As I said earlier
When u declare
char s[] = "abcd"

There r 2 steps

1. COnstat string allocation in memmory
2. COpying of this string char-by-char into s (a separarte memory location which is not const)

Thus, u can change s but not the other one

Amit
SOLUTION
Avatar of Axter
Axter
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks guys,

That makes it clear...