James Dickens James Dickens - 11 months ago 80
C++ Question

Understand sizeof in relation to pointers

In my C++ class my teacher gave me this code.

#include <iostream>

using std::cout;
using std::endl;

int main()
char numbers[]{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17 };
char *ptrNumber;
ptrNumber = &numbers[0];

// Address of first and last index
cout << (size_t)(ptrNumber) << " to " << (size_t)(ptrNumber + 17) << endl;

Which prints

12647972 to 12647989

Now previously I thought that the size of a pointer to a char would have 1 byte, meaning that both (size_t)(ptrNumber) and (size_t)(ptrNumber+17) would print 1. Instead it seems that the memory addresses in integer form are being printed. Where am I going wrong? Thanks.

Answer Source

What you're printing is not the size of the pointer (which btw is usually 4 or 8 bytes), but the address that the pointer stores. So the program displays the memory address where the first and last elements are located. size_t here has nothing to to with the sizeof operator; you only perform a cast. If you remove the size_t, you'll end up printing the string that's represented by the char array. But because your array doesn't represent a legal C-string (no zero terminator and non-displayable characters), you'll most likely end up with a segfault.