如果我增加一个数组变量会发生什么? [英] What happens if I increment an array variable?

查看:108
本文介绍了如果我增加一个数组变量会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是不是安全的,如果它奠定了堆,因为后来释放它会带来一些麻烦改变一个指针的地址,但它是安全的时候,如果指针在堆栈上声明?

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?

我说的是这样的:

char arr[] = "one two three";
arr++;
//or arr--;

我希望我说对了参照一个字符数组的指针。

I hope I got that right by referring to a char array as a pointer.

推荐答案

您不能更改数组的地址。它会给一个编译时错误。看看: HTTP://$c$cpad.org/skBHMxU0

you cannot change the address of an array. It will give a compile time error. have a look: http://codepad.org/skBHMxU0

编辑:
结果的评论让我明白自己真正的意图:
是这样的:


the comments made me realize your true intent: something like:

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

有与它没有问题。字符串一二三是一个常数,你可以随意修改 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]

作为一个经验法则,你有责任为你使用malloc /新专门分配的内存,编译器负责其余部分。

As a thumb rule, you are responsible for the memory you specifically allocated using malloc/new, and the compiler is responsible for the rest.

这篇关于如果我增加一个数组变量会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆