将size_t变量添加到指针 [英] Adding a size_t variable to a pointer
问题描述
我想将size_t类型添加到指针.像这样:
I want to add a size_t type to a pointer. Some like this:
void function(size_t sizeA,size_t sizeB){
void *pointer;
pointer=malloc(sizeA);
pointer=pointer+sizeB;
}
在这种情况不会以段错误结束的情况下,问题是:我可以这样做吗?将类型size_t添加到指针?结果地址将在地址大小"中?
In the hipothetic case that this will not end in a segfault, the question is: Can I do this? Add a type size_t to a pointer? And the resulting address will be in the address 'size'?
推荐答案
我可以[将
size_t
添加到指针]吗?
Can I do this [add
size_t
to a pointer]?
是的,只要您将void
指针强制转换为其他类型,就可以:
Yes, you can, provided that you cast void
pointer to some other type:
pointer = ((char*)pointer) + sizeB;
指针的类型决定指针要前进多少.如果强制转换为char*
,则sizeB
的每个单位对应一个字节.如果强制转换为int*
,则sizeB
的每个单位对应于在系统上存储int
所需的字节数,依此类推.
The type of the pointer determines by how much the pointer is to be advanced. If you cast to char*
, each unit of sizeB
corresponds to one byte; if you cast to int*
, each unit of sizeB
corresponds to as many bytes as it takes to store an int
on your system, and so on.
但是,必须确保sizeB
缩放为要投射到的指针的大小小于或等于sizeA
,否则结果指针将无效.如果要创建可以取消引用的指针,则缩放后的sizeB
必须严格小于sizeA
.
However, you must ensure that sizeB
scaled for size of pointer to which you cast is less than or equal to sizeA
, otherwise the resultant pointer would be invalid. If you want to make a pointer that can be dereferenced, scaled sizeB
must be strictly less than sizeA
.
这篇关于将size_t变量添加到指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!