0

I've just started learning C++ so I'm fairly sure the answer may be a simple one. As a test I'm just setting up an array and then wanting to print out the array by looping through it.

My code is below. It prints out my array as expected but then prints out a load of other numbers below it. What are these numbers and where are they coming from? I suspect that 'sizeof' isn't the best to use. All of the examples i've found are alot more complicated than I need. In any case I am interested to understand the extra numbers. Any insight available?

int age[4];
age[0]=23;
age[1]=34;
age[2]=65;
age[3]=74;

for (int i = 0; i <= sizeof(age); i++)
  cout << age[i] << endl;
return 0;

...output:

23
34
65
74
4
2147307520
0
2293608
4198582
1
3084992
3085608
-1
2293592
1980179637
-725187705
-2
1
  • In addition to the points made about the proper use of sizeof, notice that you should be looping while the index is strictly less than the array size, not less-than-or-equal. You don't want to run the loop when the index is equal to the array size, because that index doesn't exist. (The code you use to set the array values should have given you a hint there ;) ) Commented Nov 24, 2011 at 23:42

6 Answers 6

4

sizeof gives the size of an object in bytes. If the array elements are larger than one byte (as int usually is), the number will be larger than the array size.

One way to get the number of elements in an array is to divide by the size of an element:

for (size_t i = 0; i < sizeof(age)/sizeof(age[0]); i++)
    std::cout << age[i] << '\n';

(note that you also need < rather than <=, or you'll still step off the end).

Another way is to pass a reference to the array to a function template, instantiated for the array size:

template <typename T, size_t size>
void print(T (&array)[size])
{
    for (size_t i = 0; i < size; ++i)
        std::cout << array[i] << '\n';
}

print(age);

Yet another way is to use a std::vector or std::array instead of a plain array:

std::array<int, 4> age;
age[0]=23;
age[1]=34;
age[2]=65;
age[3]=74;

for (size_t i = 0; i < age.size(); ++i)
    std::cout << age[i] << '\n';
Sign up to request clarification or add additional context in comments.

2 Comments

What about the off-by-one mistake on the original for?
Thanks everyone for the replies, I understand this now, cheers Mike for the thorough answer.
2
sizeof(age) == sizeof(int) * number_of_elements ==>
   number_of_elements = sizeof(age) / sizeof(int)

Then your code becomes:

for (int i = 0; i < sizeof(age)/sizeof(age[0]); ++i)
  cout << age[i] << endl;

In C++ you may write a function to calculate the size for you(doesn't work with dynamic arrays):

template <class T, std::size_t size>
std::size_t array_size( T(&arr)[size] )
{
   return size;
}

If you are up to C++11, you could go with for-each loop:

for(int element : age){
    ....
}

Also, free-function form of std::begin and std::end can do the job:

for(auto b = std::begin(age); b != std::end(age); ++b){
    ....
}

Comments

0

Sould be i < 4 because sizeof(age) is 16 on a 32 bits machine.

3 Comments

thanks for the reply, that explains the extra numbers then. I'm wondering how I would loop through that array assuming I didn't know the size of it?
Mike Seymour answered to that question.
@Exbi: But you would always know the size of the array, because the array is a compile-time fixed construct. If your data structure has to grow dynamically, you cannot use arrays (instead, you need something like std::vector).
0

sizeof(age) is the number of bytes of age, not the number of elements.

Divide it by the size of an element of age to get that:

for (int i = 0; i < sizeof(age) / sizeof(*age); i++)
  cout << age[i] << endl;

Note: for dynamic arrays, you have to store the size of the array separately:

std::size_t size = 4; // size_t corresponds to maximum size an array can hold
int* age = new int[size];
for (int i = 0; i < size; i++)
  cout << age[i] << endl;

The other numbers are garbage past the end of the array.

age[10] is undefined behavior, which is essentially garbage numbers.

Comments

0

Sizeof is age array is 16 bytes I.e. Sizeof(int) * 4. You need array length.

Comments

0

Since sizeof(age) returns 16, you have your 4 values plus 12 ones whose value comes from the memory that is right after your array. Values in those memory segment is random, depending on what has been stored there right before you launched your program. If you used a memory check tool, you would have had an error since this memory is probably not allocated for your program.

As the other ones said, you should probably giving the exact number of element in your array as an additional variable.

const int COUNT = 4;
int age[COUNT];
age[0]=23; age[1]=34; age[2]=65; age[3]=74;
for (int i = 0; i < COUNT; ++i)
{
    cout << age[i] << endl;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.