I’m trying to figure out why this doesn’t work:
#include <stdio.h>
int main ()
{
char *orig = "Hey you guys.";
char *str;
str = &orig;
while(*str++) {
if (*str == 'y')
*str = '@';
}
puts(orig);
return 0;
}
// OUTPUT => "Hey you guys."
// Not "he@ @ou gu@s." as expected.
By assigning str = &orig, I thought that str would share the same memory address as orig.
What am I missing?
(1) for sharing memory you want to do
str = orig, sincestris already a pointer type.(2)
origis defined as a string literal, a constant – so you cannot modify the value"Hey you guys.", even not when accessing it viastr, it will result in a run time error.EDIT: Issue #3: In your while loop, you first increase the pointer, and only then checks if it is ‘y’ and modify. By doing so – you will miss the first element.
"yasdf"will become"yasdf"and not"@asdf", as you expect. [well I think that what you expect anyway…]To achieve what you are after, you can follow this: [using strcpy and a buffer, to avoid writing on constant memory]