取消引用多维数组名称和指针算术
我有这个多维数组:
char marr[][3] = {{"abc"},{"def"}};
现在,如果我们遇到定义的表达式 *marr
(ISO/IEC 9899:1999),它会说(我引用)
如果操作数的类型为“指向类型的指针”,则结果的类型为“type”
并且在该表达式中,marr 衰减为指向其第一个元素的指针,在本例中是指向数组的指针,因此我们返回“type” ' 当我们有表达式 *marr 时,大小为 3 的数组。所以我的问题是,为什么当我们执行 (*marr) + 1 时,我们仅向地址添加 1 个字节,而不是数组大小的 3 个字节。
请原谅我的无知,我不是一个很聪明的人,有时我会被这样的琐事困住。
谢谢您的宝贵时间。
I have this multi-dimensional array:
char marr[][3] = {{"abc"},{"def"}};
Now if we encounter the expression *marr
by definition (ISO/IEC 9899:1999) it says (and I quote)
If the operand has type 'pointer to type', the result has type 'type'
and we have in that expression that marr decays to a pointer to his first element which in this case is a pointer to an array so we get back 'type' array of size 3 when we we have the expression *marr. So my question is why when we do (*marr) + 1 we add 1 byte only to the address instead of 3 which is the size of the array.
Excuse my ignorance I am not a very bright person I get stuck sometimes on trivial things like this.
Thank you for your time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
递增
(*marr)
向前移动 1 个字节的原因是*marr
引用了char[3]
,{" abc"}
.如果您还不知道:如果您只有
char single_array[3] = {"abc"};
,您预计single_array + 1
会前进多远在记忆中?向右 1 个字节,而不是 3 个字节,因为该数组的类型是char
并且sizeof(char)
是 1。如果您执行了
*(marr + 1)< /code>,那么您将引用
marr[1]
,您可以预期它距离 3 个字节。marr + 1
的类型为char[][3]
,增量大小为sizeof(char[3])
。上面两个示例的主要区别在于:
char[3]
,然后递增,因此增量大小为sizeof(char
)。char[][3]
,因此增量大小为sizeof(char[3])
,然后取消引用。The reason why incrementing
(*marr)
moves forward 1 byte is because*marr
refers to achar[3]
,{"abc"}
. If you don't already know:If you had just
char single_array[3] = {"abc"};
, how far would you expectsingle_array + 1
to move forward in memory? 1 byte right, not 3, since the type of this array ischar
andsizeof(char)
is 1.If you did
*(marr + 1)
, then you would be referring tomarr[1]
, which you can then expect to be 3 bytes away.marr + 1
is of typechar[][3]
, the increment size issizeof(char[3])
.The key difference about the two examples above is that:
char[3]
, and then incremented, therefore the increment size issizeof(char
).char[][3]
, therefore the increment size issizeof(char[3])
, and then dereferencing.它加一,因为类型是 char(1 个字节)。就像:
当您取消引用
char [][]
时,它将在表达式中用作char *
。要加 3,您需要先进行算术,然后取消引用:
您正在做:
首先取消引用。
It adds one because the type is char (1 byte). Just like:
When you dereference a
char [][]
it will be used aschar *
in an expression.To add 3, you need to do the arithmetic first and then dereference:
You were doing:
which dereferences first.