Kin*_*Jnr 36 c c++ initialization shortcut multidimensional-array
我想声明一个2D数组并为其赋值,而不运行for循环.
我以为我可以使用以下想法
int array[5] = {1,2,3,4,5};
Run Code Online (Sandbox Code Playgroud)
这也适用于初始化2D阵列.但显然我的编译器不喜欢这个.
/*
1 8 12 20 25
5 9 13 24 26
*/
#include <iostream.h>
int main()
{
int arr[2][5] = {0}; // This actually initializes everything to 0.
arr [1] [] = {1,8,12,20,25}; // Line 11
arr [2] [] = {5,9,13,24,26};
return 0;
}
Run Code Online (Sandbox Code Playgroud)
J:\ CPP\Grid> bcc32.exe Grid.cpp
Borland C++ 5.5.1 for Win32版权所有(c)1993,2000 Borland
Grid.cpp:
错误E2188 Grid.cpp 11:函数main()中的表达式语法
错误E2188 Grid.cpp 12:函数main()中的表达式语法
警告W8004 Grid.cpp 14:'arr'被分配一个从未在函数main()中使用的值
*编译中的2个错误*
请帮助确定使用我的一组值初始化2d数组的正确方法.
Che*_*Alf 55
像这样:
int main()
{
int arr[2][5] =
{
{1,8,12,20,25},
{5,9,13,24,26}
};
}
Run Code Online (Sandbox Code Playgroud)
这应该由您的C++教科书涵盖:您使用的是哪一本?
无论如何,更好的是,考虑使用std::vector或一些现成的矩阵类,例如来自Boost.
在C或C++中初始化多维数组的正确方法是
int arr[2][5] = {{1,8,12,20,25}, {5,9,13,24,26}};
Run Code Online (Sandbox Code Playgroud)
如果需要,您可以使用相同的技巧初始化更高维的数组.
另外,在初始代码中要小心 - 您试图在数组中使用1索引偏移来初始化它.这没有编译,但是如果它确实会导致问题,因为C数组是0索引的!
只是想指出您不需要指定数组的所有维度.
最左边的维度可以由编译器"猜测".
#include <stdio.h>
int main(void) {
int arr[][5] = {{1,2,3,4,5}, {5,6,7,8,9}, {6,5,4,3,2}};
printf("sizeof arr is %d bytes\n", (int)sizeof arr);
printf("number of elements: %d\n", (int)(sizeof arr/sizeof arr[0]));
return 0;
}
Run Code Online (Sandbox Code Playgroud)