-1

I have tried initialising my int cate[catNum] array into all 1s, when cout<<cate[1], it outputs 0? I don't know what the problem is, theoretically it should be 1?

int main ()
{
    int const catNum = 13;    
    int cate[catNum]= {1};
    cout<<cate[1]<<endl;
}
Praetorian
  • 106,671
  • 19
  • 240
  • 328
Op-Zyra
  • 45
  • 6
  • 1
    No, it's not `1`, theoretically or otherwise. You've initialized the first element to `1` and the remaining to `0`. – Praetorian May 15 '15 at 23:28
  • See http://stackoverflow.com/questions/2625551/initializing-primitive-array-to-one-value for multiple ways to initialize all the elements in the array to the same value. – Foon May 15 '15 at 23:30
  • 1
    Duplicate of https://stackoverflow.com/q/1352370/241631 – Praetorian May 15 '15 at 23:31

2 Answers2

1
int cate[catNum]= {1};

This syntax initializes the first element to 1 and the rest to 0. (Technically, it value-initializes the rest.)

Try,

std::fill( std::begin( cate ), std::end( cate ), 1 );
Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
0

You defined cate as an array of 13 integers, but the initializer {1} has only one integer, so you only initialized the first element to 1. To set them all, you could do something like

for (int i = 0; i < catNum; i++) { cate[i] = 1; }
Hew Wolff
  • 1,489
  • 8
  • 17