Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it allowed to add a zero to a null pointer?

I know that pointer arithmetic is disallowed for null pointers. But imagine I have something like this:

class MyArray {
  int *arrayBegin;  // pointer to the first array item, NULL for an empty array
  unsigned arraySize;   // size of the array, zero for an empty array
public:
  int *begin() const { return arrayBegin; }
  int *end() const { return arrayBegin + arraySize; }  // possible? (arrayBegin may be null)

Is it possible (allowed) to have the above end() implementation? Or is it necessary to have:

  int *end() const { return (arraySize == 0) ? nullptr : (arrayBegin + arraySize); }

to avoid pointer arithmetic with nullptr because arrayBegin is null for an empty array (despite arraySize also being zero in this case)?

I know it's possible to store int *end; instead of unsigned size; and let size be computed as end-begin - but then comes the same issue: Is it allowed to compute nullptr - nullptr?

I would especially appreciate standard references.

like image 991
Jarek C Avatar asked Dec 19 '19 11:12

Jarek C


People also ask

Can we write 0 instead of null?

Essentially they are the same but '\0' is for characters as opposed to null which is the idea and representation that an object has yet to be defined/set to a meaningful value.

Can we assign 0 to pointer?

You can assign 0 into a pointer: ptr = 0; The null pointer is the only integer literal that may be assigned to a pointer.

Is it safe to free a null pointer?

It is safe to free a null pointer. The C Standard specifies that free(NULL) has no effect: The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation.

Can a pointer be 0 in C++?

All pointers, when they are created, should be initialized to some value, even if it is only zero. A pointer whose value is zero is called a null pointer.


1 Answers

Yes, you can add zero to the null pointer and subtract one null pointer from another. Quoting Additive operators [expr.add] section of the C++ standard:

When an expression J that has integral type is added to or subtracted from an expression P of pointer type, the result has the type of P.

  • If P evaluates to a null pointer value and J evaluates to 0, the result is a null pointer value.
like image 87
Sergey Strukov Avatar answered Oct 26 '22 12:10

Sergey Strukov