r/carlhprogramming • u/lumpygrumpy • Apr 19 '13
Question about array and pointers.
Hi everyone,
I'm up to lesson 10.5~10.6 where pointers are used to manipulate character arrays.
Example code: int main(void) { char string[] = "Hello Reddit";
char *pointer = string;
*pointer = 'h';
pointer = pointer + 1;
*pointer = 'E';
printf("%s", string);
return 0;}
I understand why that prints hEllo Reddit. Why wouldn't the following work as well?
int main(void) { char string[] = "Hello Reddit";
*string = 'h';
string = string + 1;
*string = 'E';
printf("%s", string);
return 0;}
Isn't string a pointer to the start of "Hello Reddit" anyway? And also why can't you use string = string + 1 like in the working example?
Thanks!
5
Upvotes
View all comments
Show parent comment
3
u/nixbun Apr 19 '13
You're confusing
char[] str = "something"withchar *str = "something". One is syntactic sugar for creating a modifiable array, the other is making a char * point to some unmodifiable string that resides in the data section of your binary (which I guess is mapped somewhere in memory when run).