str
is a 50 element char array, not a pointer. An array decays (gets converted into) to a pointer to the first element in most circumstances, but you can't modify the decayed pointer unless you do so with a copy of that pointer.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[50];
char* ptr = str;
scanf("%s", str);
while(*ptr != 0)
{
printf("%c", *ptr);
ptr++;
}
return 0;
}
As Ulrich Eckhardt pointed out, a better way to implement this is to use a for loop:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[50];
scanf("%s", str);
for(char* ptr = str; *ptr != 0; ++ptr)
{
printf("%c", *ptr);
}
return 0;
}
It's more clear this way, and the scope of ptr
is limited to the loop which is good because we don't need it later.