#include <iostream>
#include <stdlib.h>
int * coins;
int * buffer;
int sumofarray(int* array) {
int sum;
int i = (sizeof(array)/sizeof(array[0]));
std::cout << i << "\n";
return sum;
}
int main (int argc, char * const argv[]) {
int coins[] = {7, 1, 2, 8};
std::cout << (sizeof(coins)/sizeof(coins[0])) << "\n";
std::cout << sumofarray(coins);
}
so theres a dynamic array with four used cells. In main() the equation to determine how many elements it has works correctly returning 4, but when it's executed in the function (in which the same array has been passed to) it incorrectly returns 2.
If anybody has any insight they could give to help me with this that'd be greatly appreciated.
c/c++ doesn't store the size of the array. sizeof(array) returns the size of the pointer, not the size of the array.
Basically sizeof calculates the size of the datatype. Not what's in the data type. So you gotta remember how large your array is when you make it. Of course if you want a dynamic array you can use a vector.
I'm sort of guessing what you're trying to do but this might work:
#include <iostream>
#include <stdlib.h>
using namespace std;
int * coins;
int sumofarray(int* array, int len) {
int sum;
for (int i = 0; i < len; i++) {
sum += array[i];
}
return sum;
}
int main (int argc, char * const argv[]) {
int coins[] = {7, 1, 2, 8};
cout << "Number of elements: 4" << endl;
cout << sumofarray(coins, 4);
}