Andres Olivares Andres Olivares - 28 days ago 13
C Question

Adding a size_t variable to a pointer

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

Answer

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.

Comments