1

I have a question concerning the sizeof(array)/sizeof(array[0]), especially when you use it within a function. I wanted to get the size of the array (number of elements in that array) through that expression, however it gives me unexpected behavior. When I enter 5 for n, within the function calculateSum I cannot receive the array length of 5 when I use sizeof(a)/sizeof(a[0]). I am still a beginner in C++, can you give some explanation to this kind of behavior? Why is it safer to pass the length of the array as a parameter?

Here is a sample input: 5 (length) 1 2 3 4 5 (input for a) 4 5 3 2 10 (input for b)

The lengths of a, b, and c are the same. Thank you very much.

#include<iostream>
using namespace std;


int * calculateSum(int a[], int b[]){
    int* c = new int[sizeof(a)/sizeof(a[0])];

    for(int i = 0;i < sizeof(a)/sizeof(a[0]);i++){
        c[i] = a[i]+b[i];
    }
    return c;
};

int main(){
    int n = 0;
    cin>>n;
    int a[n];
    int b[n];
    // enter everything for array a first and elements of array b
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    for(int i=0;i<n;i++){
        cin>>b[i];
    }


    int *c;
    c=calculateSum(a,b);

    for(int i=0;i<n;i++){
        cout<<*(c+i)<<" ";
    }

    delete[] c;
    return 0;
}

  • In main, `a` and `b` are arrays, and the compiler knows their length. When passed into a function, they are just pointers, which have no clue about length, and `sizeof(a)` is the size of the pointer datatype (typically, 8 on 64-bit systems, 4 before that). – Amadan Dec 02 '19 at 04:30
  • Also, the declaration `int a[n];` where the value of `n` is not known at compile time is not Standard C++. It's a compiler extension. – aschepler Dec 02 '19 at 04:32

0 Answers0