2D array values C++

后端 未结 5 428
鱼传尺愫
鱼传尺愫 2020-12-05 09:34

I wanted to declare a 2D array and assign values to it, without running a for loop.

I thought I could used the following idea

int array[5] = {1,2,3,         


        
5条回答
  •  天涯浪人
    2020-12-05 10:16

    The proper way to initialize a multidimensional array in C or C++ is

    int arr[2][5] = {{1,8,12,20,25}, {5,9,13,24,26}};
    

    You can use this same trick to initialize even higher-dimensional arrays if you want.

    Also, be careful in your initial code - you were trying to use 1-indexed offsets into the array to initialize it. This didn't compile, but if it did it would cause problems because C arrays are 0-indexed!

提交回复
热议问题