简体   繁体   中英

why i cant cout the array in the second loop when i use sizeof(array)/sizeof(array[0]) as a condition for the for loop?

why i cant cout the array in the second loop when i use sizeof(array)/sizeof(array[0]) as a condition for the for loop?

#include <iostream>
    using namespace std;
    
    int main(){
        int num;
        int array[] = {};
        cout << " enter the numbers " << endl;
        for (int i = 0 ; i < 5 ; i ++ )
            cin >> array [i];
        num = sizeof(array)/sizeof(array[0]); 
            for ( int x = 0 ; x < num  ; x ++)
            cout << array[x] << endl;
            

Your array has size 0.

int array[] = {};

This initializes the array with a size of 0. It's the same as doing

int array[0];

Arrays like these cannot grow or shrink, so they cannot change their size. What you likely want to do is

int array[5];

which gives it a size of 5 . Further your sizeof code will then work as well. I assumed you want a size of 5 since your first loop goes to 5.

Note that these really cannot ever change size. You make it size 0, it stays size 0, no matter what you do after. In my suggested fix, its size 5, and it will stay size 5, you can't resize it.

By the way, writing to locations 0-5 on an array with size 0 like you do is not okay, since the array does not have any such index. It's undefined behavior to access positions out of bounds of this array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM