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

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

c++ - What happens if I increment an array variable?

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...