I know that it isn't safe to change a pointer's address if it lays on the heap because freeing it later would cause some trouble, but is it safe to do that if the pointer is declared on the stack?
I'm talking about something like this:
char arr[] = "one two three";
arr++;
//or arr--;
I hope I got that right by referring to a char array as a pointer.
It's not where the pointer lives (heap or stack), but where the memory the pointer points to lives.
Memory on the stack is cleaned up automatically, you have to remember (keep pointers to) memory on the heap, because it's your responsibility to clean it up.
As written, your code won't work because the operand of
++
must be a modifiable lvalue, and array expressions are not modifiable lvalues.What you can do is something like this:
As far as safety is concerned, you can still run into problems if the result of incrementing or decrementing
ptr
causes it to point to memory outside of the array, which may or may not be safe to access or modify.you cannot change the address of an array. It will give a compile time error. have a look: http://codepad.org/skBHMxU0
EDIT:
the comments made me realize your true intent: something like:
There is no problem with it. the string "one two three" is a constant, and you can freely modify
ptr
, but note you might have troubles later finding the start of this string again... [but memory leak will not occur]As a thumb rule, you are responsible for the memory you specifically allocated using malloc/new, and the compiler is responsible for the rest.
You can not increment an array variable / array name, however you can access any element of the array by using array name / array variable. That is the reason why pointers came in to picture,. Array addresses are unmodifiable For example,
here in above snippet, Line 2: We are not incrementing array variable, however we are fetching the value of 1st indexed element in the array by using array address.
The line:
creates an array (which means its location is FIXED), it is not the same thing as a pointer as a pointers location can be moved. The array is default-initialized with the contents "one two three"; You can change the contents of the array as log as it doesn't grow in size, but you can't move arr.
would thus be an error. You could, however, do:
to get to the second character of the arr array.