You are incrementing ptr
, therefore changing the address that it points to. You can’t do that.
In your case, have a separate pointer, let’s say char * p = ptr
and do your operations with p
leaving ptr
intact so you can free(ptr)
later.
EDIT Taking a second look at your code, I found that you are doing ptr++
when you shouldn’t. You are accessing the characters in the array like ptr[i]
, if you mess with the ptr
pointer, you are changing the base address and accessing the characters with ptr[i]
can lead (and will lead) to unexpected results.
If you simply remove that line (ptr++
) your code will magically work. If you want to explore the pointer concept and try another solution, your code could look something like this:
int main(int argc, char *argv[]){ char *ptr = NULL; char * p; ptr = (char *) malloc(LEN+1);// +1 for string (please check for NULL) p = ptr; strcpy(ptr, "hello"); int i = 0; while (*p) // note how I changed it to a while loop, C strings are NULL terminated, so this will break once we get to the end of the string. What we gain is that this will work for ANY string size. { printf("ptr[%d] = %c\n", i++, *p); // here i dereference the pointer, accessing its individual char p++; } free(ptr); return 0; }