Zatharan Zatharan - 1 year ago 59
C++ Question

sum of values in array returns memory address unless sizeof(array)/2

Here is the program I'm working on, it's simple but helps me to figure out the basics of C++. I'm struggling with pointers and try to understand how it works.

int main()

unsigned int note;
unsigned int nombreDeNotesASaisir = 0;
unsigned int totalDesNotes = 0;

cin >> nombreDeNotesASaisir;

int* tableauDeNotes = new int[nombreDeNotesASaisir] {};

for (int i = 0; i < nombreDeNotesASaisir; i++)
cin >> note;
tableauDeNotes[i] = note;

// method that is supposed to make the sum of all the values inside the array

for (int i = 0; i < sizeof(tableauDeNotes); i++)
totalDesNotes += *(tableauDeNotes + i);

cout << "le total des notes est de :" << totalDesNotes << "\n";

//print the average of all the marks

unsigned int moyenne = totalDesNotes / nombreDeNotesASaisir;
cout << moyenne << ' ';

return 0;

I cant seem to get the result of the operation, instead i think i get the memory address, why is that and what can I do to get it working ?

PS: the weird thing is that when i divide the sizeof(array)/2 it returns the correct sum of the values

Answer Source

Operator "sizeof" does not return the number of elements in the array. Instead it returns the size of the passed variable.

In your case the passed variable is a pointer not an array! Size of a pointer is 4 bytes on 32 bit architectures, and 8 bytes on 64 bit architectures. So sizeof(tableauDeNotes) returns 4 or 8.

If you had a variable like this:

int myTable[5];

Then this would be an array. sizeof(myTable) would return total size of myTable, which is:

sizeof(myTable) = 5 * sizeof(int)

So depending on the architecture it will be for 32 bit ints: 5 * 4 = 20 or for 64 bit ints: 5 * 8 = 40.

If you would like to get number of elements in myTable, you could use this:

int numElements = sizeof(myTable) / sizeof(int);

But it works for tables only, not for pointers as in your case.

In your case you should just use nombreDeNotesASaisir instead of sizeof operator.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download