Daily Weekly Monthly

Daily Shaarli

All links of one day in a single page.

February 6, 2021

getting size of array from pointer c++ - Stack Overflow

I am writing a simple function that returns the largest integer in an array. The problem I am having is finding the number of elements in the array.

Here is the function header:

int largest(int ...

getting size of array from pointer c++ - Stack Overflow

C++ is based on C and inherits many features from it. In relation to this question, it inherits something called "array/pointer equivalence" which is a rule that allows an array to decay to a pointer, especially when being passed as a function argument. It doesn't mean that an array is a pointer, it just means that it can decay to one.

void func(int ptr); int array[5]; int ptr = array; // valid, equivalent to 'ptr = &array[0]' func(array); // equivalent to func(&array[0]);

This last part is the most relevant to your question. You are not passing the array, you are passing the address of the 0th element.

In order for your function to know how big the incoming array is, you will need to send that information as an argument.

static const size_t ArraySize = 5; int array[ArraySize]; func(array, ArraySize);

Because the pointer contains no size information, you can't use sizeof.

void func(int* array) { std::cout << sizeof(array) << "\n"; }

This will output the size of "int*" - which is 4 or 8 bytes depending on 32 vs 64 bits.

Instead you need to accept the size parameters

void func(int* array, size_t arraySize); static const size_t ArraySize = 5; int array[ArraySize]; func(array, ArraySize);

Even if you try to pass a fixed-sized array, it turns out this is syntactic sugar:

void func(int array[5]);

http://ideone.com/gaSl6J

Remember how I said that an array is NOT a pointer, just equivalent?

int array[5]; int* ptr = array; std::cout << "array size " << sizeof(array) << std::endl; std::cout << "ptr size " << sizeof(ptr) << str::endl;

array size will be 5 sizeof(int) = 20 ptr size will be sizeof(int ) which will be either 4 or 8 bytes.

sizeof returns the size of the type being supplied, if you supply an object then it deduces the type and returns the size of that

If you want to know how many elements of an array are in the array, when you have the array and not a pointer, you can write

sizeof(array) / sizeof(array[0])

or sizeof(array) / sizeof(*array)