请问C++中二维数组的问题
PHPz
PHPz 2017-04-17 11:48:31
0
2
543

C++中 二维数组如何初始化为空的?
这样可以吗?
int temp[][3]={};
求教 谢谢!

PHPz
PHPz

学习是最好的投资!

reply all(2)
迷茫

There is no such thing as "empty array" in C++. In fact, you don't need a truly empty array. Arrays are used for reading and writing. What’s the use of leaving them empty? If you don't want to see some element in the array, just don't read it. Declare an array, and the system will allocate a correspondingly sized space on the stack for you. If the array is initialized, for example,

    int temp[][3] = {0};

Then 0s are written into this space. However, this declaration method lacks the first dimension, so it causes confusion: How big is this space? Generally speaking, it should be 3*sizeof(int), that is, this array is filled with 3 0s. If initialized like this:

    int temp[][3] = {0, 1, 2};

The size of the array is still 3*sizeof(int). But what if you initialize it like this:

    int temp[][3] = {0, 1, 2, 3};

The size of this array is 6*sizeof(int). The reason is: 3 columns were originally declared, but there were 4 ints during initialization, so the system automatically added another row to the array. In the same way, if initialized like this:

    int temp[][3] = {0, 1, 2, 3, 4, 5};

Then the array size is still 6*sizeof(int), and initialized like this:

    int temp[][3] = {0, 1, 2, 3, 4, 5, 6};

At this time, the array size is 9*sizeof(int).
However, if you don't initialize the array, for example:

    int temp[][3];

Generally it cannot be compiled. The reason is very simple. If the first dimension m and the second dimension n are given at the same time, then the array space will be allocated according to m*n ints; if only the second dimension n is given, then the system needs to comprehensively consider n and your actual The initialized data allocates space for the array; if you don't even initialize it, the system will be dumbfounded and doesn't know how much space should be allocated, so a compilation error will be reported.

小葫芦
int temp[这里必须要有一个数字][3]={0};
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template