Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
358 views
Welcome To Ask or Share your Answers For Others

1 Answer

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:

char *ptr = "one two three";
ptr++;

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...