C++ 中的指针算术使用 sizeof(type) 增量而不是字节增量? [英] Pointer arithmetics in C++ uses sizeof(type) incremention instead of byte incremention?
问题描述
我对 C++ 中指针算术的行为感到困惑.我有一个数组,我想从当前数组向前移动 N 个元素.由于在 C++ 中指针是以字节为单位的内存地址,因此代码为 newaddr = curaddr + N * sizeof(mytype)
对我来说似乎合乎逻辑.但是它产生了错误;后来我发现使用 newaddr = curaddr + N
一切正常.为什么这样?真的应该是 address + N 而不是 address + N * sizeof 吗?
I am confused by the behavior of pointer arithmetics in C++. I have an array and I want to go N elements forward from the current one. Since in C++ pointer is memory address in BYTES, it seemed logical to me that the code would be newaddr = curaddr + N * sizeof(mytype)
. It produced errors though; later I found that with newaddr = curaddr + N
everything works correctly. Why so? Should it really be address + N instead of address + N * sizeof?
我注意到的部分代码(所有内存分配为一个块的二维数组):
Part of my code where I noticed it (2D array with all memory allocated as one chunk):
// creating pointers to the beginning of each line
if((Content = (int **)malloc(_Height * sizeof(int *))) != NULL)
{
// allocating a single memory chunk for the whole array
if((Content[0] = (int *)malloc(_Width * _Height * sizeof(int))) != NULL)
{
// setting up line pointers' values
int * LineAddress = Content[0];
int Step = _Width * sizeof(int); // <-- this gives errors, just "_Width" is ok
for(int i=0; i<_Height; ++i)
{
Content[i] = LineAddress; // faster than
LineAddress += Step; // Content[i] = Content[0] + i * Step;
}
// everything went ok, setting Width and Height values now
Width = _Width;
Height = _Height;
// success
return 1;
}
else
{
// insufficient memory available
// need to delete line pointers
free(Content);
return 0;
}
}
else
{
// insufficient memory available
return 0;
}
推荐答案
你的推理错误就在这里:因为在 C++ 中,指针是以字节为单位的内存地址,[...]".
Your error in reasoning is right here: "Since in C++ pointer is memory address in BYTES, [...]".
C/C++ 指针不是以字节为单位的内存地址.当然,它由内存地址表示,但您必须区分指针类型及其表示形式.操作+"是为类型定义的,而不是为它的表示定义的.因此,当它被称为 int *
类型时,它尊重这种类型的语义.因此,在 int *
类型上的 + 1
将使指针前进的字节数与底层 int
类型表示使用的字节数一样多.
A C/C++ pointer is not a memory address in bytes. Sure, it is represented by a memory address, but you have to differentiate between a pointer type and its representation. The operation "+" is defined for a type, not for its representation. Therefore, when it is called one the type int *
, it respects the semantics of this type. Therefore, + 1
on an int *
type will advance the pointer as much bytes as the underlying int
type representation uses.
你当然可以像这样投射你的指针:(int)myPointer
.现在您有一个数字类型(而不是指针类型),其中 + 1
将按照您对数字类型的预期工作.请注意,在此转换之后,表示保持不变,但类型发生了变化.
You can of course cast your pointer like this: (int)myPointer
. Now you have a numeric type (instead of a pointer type), where + 1
will work as you would expect from a numeric type. Note that after this cast, the representation stays the same, but the type changes.
这篇关于C++ 中的指针算术使用 sizeof(type) 增量而不是字节增量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!