A
A
Alexander Vasilenko2016-03-25 06:40:29
C++ / C#
Alexander Vasilenko, 2016-03-25 06:40:29

Why is only the first element of the array passed to the function?

Very noob question.
There is an array:
int my_array[5] = { 1, 2, 3, 4, 5 };
There is a function that is created to print this array to the console:

void print_array(int my_array[]){
  using namespace std;
  cout << "ARRAY = { ";
  int size_of_array = sizeof(my_array) / sizeof(int);
  for (int i = 0; i < size_of_array; i++){
    cout << my_array[i] << " ";
  }
  cout << "}" << endl;
}

Let's use this function:
print_array(my_array);
For some unknown reason, only the first element of the array (1) is passed.
ARRAY = { 1 }

But why?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
AxisPod, 2016-03-25
@SanchelliosProg

Apparently you are compiling a 32-bit binary, if it were 64-bit, it would show 2 elements. Because sizeof(my_array) in your case will not return the size of the array, but the size of the pointer to the array, and it is always equal to sizeof(int) in your case. The size must be thrown from the outside. The compiler does not carry the size of an array along with the array.

D
Daniil Demidko, 2016-03-25
@Daniro_San

Well, on the plus side, arrays are not passed by value. A pointer to an array is always passed, be it an array or even a matrix. Or more precisely, a pointer to the first element. This is the legacy of C, where arrays are closely related to pointers. Among other things, thanks to this feature, memory on the stack is not allocated once again - when passing arguments.
void anyFunc(int myArray[]) in this case is just a convenient syntax to show that it is the pointer to the array that is being passed, void anyFunc(int *myArray) is the same.
It is possible, as Stroustrup recommends in such cases, to define a structure that stores a pointer to an array and its size and accept it in a function.

struct Arr{ 
    int *arrPtr;
    int Size;
}

void print_array(const Arr &arr){ ... }

And calling your function will be reduced to this action:
But it's best to use std::vector wherever there is no memory limit.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question