I’m trying to learn more about arrays since I’m new to programming. So I was playing with different parts of code and was trying to learn about three things, sizeof(). How do I find the length of an array, and also how do I put arrays into functions (as a parameter)?
My code is:
#include <iostream>
using namespace std;
void arrayprint(int inarray[])
{
for (int n_i = 0 ; n_i < (sizeof(inarray) / sizeof(int)) ; n_i++)
{
cout << inarray[n_i] << endl;
}
}
int main()
{
int n_array[5];
for (int n_i = 0 ; n_i < (sizeof(n_array) / sizeof(int)) ; n_i++ )
{
cin >> n_array[n_i];
}
arrayprint(n_array);
return 0;
}
It seems the sizeof(inarray) / sizeof(int) works in the main function, but not in the arrayprint function. In the array print function, it evaluates to 1, while in main it evaluates to 5. Why?
So I guess what I want to know is how they are different? And why?
This
Is equivalent to this:
So you are getting the size of an int pointer on your machine. Even if your question is about C++ and your function looks a bit different, it boils down to this C FAQ entry.
So, inside
mainn_arrayis actually a true honest array. But when passed to a function, it “decays” into a pointer. And there’s no way to know the real size. All you can do is pass additional arguments to your function.And call it like this:
Of course, the real solution would be to use
vectors since you’re using C++. But I wouldn’t know much about C++.