将size_t变量添加到指针 [英] Adding a size_t variable to a pointer

查看:99
本文介绍了将size_t变量添加到指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将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屋!

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