Adding a size_t variable to a pointer

我只是一个虾纸丫 提交于 2019-12-12 18:34:36

问题


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;
}

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'?


回答1:


Can I do this [add size_t to a pointer]?

Yes, you can, provided that you cast void pointer to some other type:

pointer = ((char*)pointer) + sizeB;

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.

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.



来源:https://stackoverflow.com/questions/40444891/adding-a-size-t-variable-to-a-pointer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!