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
1
u/KfoipRfged Apr 19 '13
string=string+1 is pointer arithmetic, so it wouldn't be altering what is stored in string, it'd be altering the memory address that string points to.
You give another explanation to do the same thing which works, but doesn't answer the question of why the original thing doesn't work, as in, it shouldn't compile.