Your approach is wrong. Your code does not search for the last element of the array , look for the first element that is 0
, which is not much the same.
In C ++, an array is nothing more than a succession of data in memory. It does not have tagged any information about its size, nor any end of fix mark or anything like that. It is not more than a group of data, mixed with all the other data that is in the memory of the team.
That's why your code fails. Find a 0
, and you will surely find it, but there is no way to know exactly where you will find it. Of course, there are none in the values of your array .
You have to change your approach:
- You can call your function with an argument that indicates the size.
In that case, you have to change the way you call it and what the function does:
int ultimo_elem (int x[], size_t size ) {
return ( size / sizeof( x[0] ) ) - 1;
}
cout << ultimo_elem( array, sizeof( array ) ) << endl;
- You can indicate an exact size in the array that you expect.
But then, you will not be able to use the function with arrays of other sizes:
int ultimo_elem (int x[10]){ return 9; }
cout << ultimo_elem( array ) << endl;
- You can put your own brand in the last value of the array.
It's the least changes you need:
int array[] = { 23, 43, 35, 38, 67, 12, 76, 10, 34, 8, 0 };
- You can make a template that works for different sizes.
I think it's still early for you to consider this option: -)