4

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

  • Short answer is yes. For pointer arithmetic see http://stackoverflow.com/questions/394767/pointer-arithmetic – sg7 Nov 06 '16 at 00:58
  • @sg7 It's trickier than that, because C does not allow pointer arithmetics on `void*`. – Sergey Kalinichenko Nov 06 '16 at 01:01
  • @dasblinkenlight you are right about C. My C++14 compiler gives just a warning: "pointer of type 'void *' used in arithmetic." – sg7 Nov 06 '16 at 01:14

1 Answers1

4

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • First paragraph is a nice description of what is frequently called the "stride" of pointer arithmetic. The OP would do well to commit it to memory. – WhozCraig Nov 06 '16 at 01:03
  • what if we casted it to `void*` instead of `char*` ? – Bite Bytes Aug 04 '17 at 20:30
  • Late comment, but for those who come across this in the future -- first, the best practice is to cast to a `uintptr_t` for adding `size_t`'s. (see ``). Next, if you add an integer to a `void` pointer, some compilers will add `sizeB` to pointer, as if pointer were a `uintptr_t` (i.e. add `sizeB * 1`). Other compilers will generate an error. In any case, it's not portable. – HardcoreHenry Jan 31 '19 at 19:49
  • 1
    Late comment, but for those who come across this in the future: The `` above should be a ``. – Multisync Aug 06 '22 at 08:23