Answer the question
In order to leave comments, you need to log in
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;
}
print_array(my_array);
ARRAY = { 1 }
Answer the question
In order to leave comments, you need to log in
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.
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){ ... }
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question