1

Let's consider the following code:

#include <iostream>
using namespace std;

void foo(int * arr)
{
    cout << sizeof(arr) << endl;
}

int main()
{
    int arr[3] = {1, 2, 3};
    cout << sizeof(arr) << endl;
    foo(arr);
}

Since array name decay into pointer to its first element, why does sizeof(arr) inside foo() returns 8 instead of 4?

3
  • 1
    Because on your system the size of a pointer is 8? (Which is common on 64-bit platforms) Commented Apr 15, 2020 at 18:20
  • In C++ you should pass either std::vector or std::array depending on your use case. Otherwise it is canonical in C APIs to pass two params per array: first the pointer to the array, second the number of elements. Commented Apr 15, 2020 at 18:22
  • 1
    @michalt38 Please reread what you wrote yourself. "Since array name decay into pointer to its first element, why sizeof(arr) inside foo() returns 8 instead of 4?" Sometimes it is very useful to understand what you are writing. Commented Apr 15, 2020 at 18:42

3 Answers 3

2

In most cases the size of a pointer is 8 bytes. In your system that is the size of the pointer.

Note that the size of the pointer, and you probably know this, is not the size of the object it points or the size of the type of object.

The size of a pointer depends on several factors, like the CPU architecture, compiler or Operating System.

The way it usually works is if the system is 16-bit, the of size pointers is 2 bytes, if the system is 32-bit, the size is 4 bytes, if it is 64-bit, it's 8 bytes.

Sign up to request clarification or add additional context in comments.

Comments

1

The argument that you are passing to your function is the address of the first element of your array. It means that in the function you see only the address of the array you declared inside main scope. If you want to treat an array same as you treat it inside main function, you should pass its size to function as an argument also. If your array has always a fixed-size, then you dont have to this. I would like to add that the sizeof(arr) will never not return the same value with the main scope one.

The result of sizeof(arr) inside the function is the result of sizeof(int*)

Comments

1

When you assigned an array to a pointer, and use sizeof operator for pointer, the sizeof will return the size of pointer(not the array). So in foo function, sizeof return int * size in byte.

Also, you can use array instead built-in array. array know it size but built-in array wont.

Caution: Type sizes are platform dependent.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.