Share your repls and programming experiences

← Back to all posts
Help!!!
MoNur (0)

I'm new to C++ and I need your help! whenever I try to use size in my code it says size is undeclared. how should I declare it?!

My head is about to explode!!!!

Voters
MoNur (0)
Commentshotnewtop
MoNur (0)

@mwilki7

size(storSpace) is basically storage space. so I'm looking for total space in that array...I don't know if that makes sense

mwilki7 (775)

@MoNur
I think you want to be using sizeof instead of size
Using sizeof on a local array will give you the size in bytes.
Divide by the byte size to get the number of elements.

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int storSpace[] = { 232,241,324,216,221,298,334,212,235,324,264,141 };
    cout << "Size of array (bytes): " << sizeof(storSpace) << endl;
    
    // sizeof(int) because storSpace is an int array
    cout << "Size of array (elements): " << sizeof(storSpace) / sizeof(int) << endl;

    return 0;
}

Output:

Size of array (bytes): 48
Size of array (elements): 12

If you don't have to use arrays, I would suggest using vectors so you don't have to do any length tracking or math in size calculation.

MoNur (0)

@mwilki7 thanks a lot mate. I got it now

mwilki7 (775)

Arrays don't have information about themselves other than what the first element is. You will have to keep track of its size.

Would you mind adding some indentation to your code? It would make it easier to see.
Also, what does size(storSpace) do?