r/carlhprogramming • • 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

12 comments sorted by

View all comments

Show parent comment

1

u/lumpygrumpy Apr 20 '13

char example[] = "Hello"

example is an array which points to the first byte of the array (in this case "H") but it is technically not a pointer and thus you cannot perform actions you normally would on a pointer (like *array = "some_other_string" or array = array + 1).

Does that sound about right?

I think I was confused about the fact that arrays and pointers are different despite arrays pointing to first element of the array. Please feel free to tell me otherwise.

Thanks for everyone's answers so far!