📜  在C / C++中初始化多维数组

📅  最后修改于: 2021-05-30 07:15:34             🧑  作者: Mango

在C / C++中,多维数组的初始化可以将大多数维保留为可选。除最左边的尺寸外,还必须指定所有其他尺寸。
例如,以下程序在编译中失败,因为未指定两个维度。

C
#include
int main()
{
  int a[][][2] = { {{1, 2}, {3, 4}},
                   {{5, 6}, {7, 8}}
                 };  // error
  printf("%d", sizeof(a));
  getchar();
  return 0;
}


C++
#include
using namespace std;
int main()
{
  int a[][][2] = { {{1, 2}, {3, 4}},
                   {{5, 6}, {7, 8}} };  // error
  cout << sizeof(a);
  getchar();
  return 0;
}
 
// This code is contributed by Mayank Tyagi


C
// Program 1
#include
int main()
{
  int a[][2] = {{1,2},{3,4}}; // Works
  printf("%lu", sizeof(a)); // prints 4*sizeof(int)
  getchar();
  return 0;
}


C++
// Program 1
#include
using namespace std;
int main()
{
  int a[][2] = {{1, 2}, {3, 4}}; // Works
  cout << sizeof(a); // prints 4*sizeof(int)
  return 0;
}
 
// This code is contributed by Mayank Tyagi


C
// Program 2
#include
int main()
{
  int a[][2][2] = { {{1, 2}, {3, 4}},
                     {{5, 6}, {7, 8}}
                   }; // Works
  printf("%lu", sizeof(a)); // prints 8*sizeof(int)
  getchar();
  return 0;
}


C++
// Program 2
#include
using namespace std;
int main()
{
  int a[][2][2] = { {{1, 2}, {3, 4}},
                     {{5, 6}, {7, 8}} }; // Works
  cout << sizeof(a); // prints 8*sizeof(int)
  return 0;
}
 
// This code is contributed by Mayank Tyagi


以下2个程序正常运行。

C

// Program 1
#include
int main()
{
  int a[][2] = {{1,2},{3,4}}; // Works
  printf("%lu", sizeof(a)); // prints 4*sizeof(int)
  getchar();
  return 0;
}

C++

// Program 1
#include
using namespace std;
int main()
{
  int a[][2] = {{1, 2}, {3, 4}}; // Works
  cout << sizeof(a); // prints 4*sizeof(int)
  return 0;
}
 
// This code is contributed by Mayank Tyagi

C

// Program 2
#include
int main()
{
  int a[][2][2] = { {{1, 2}, {3, 4}},
                     {{5, 6}, {7, 8}}
                   }; // Works
  printf("%lu", sizeof(a)); // prints 8*sizeof(int)
  getchar();
  return 0;
}

C++

// Program 2
#include
using namespace std;
int main()
{
  int a[][2][2] = { {{1, 2}, {3, 4}},
                     {{5, 6}, {7, 8}} }; // Works
  cout << sizeof(a); // prints 8*sizeof(int)
  return 0;
}
 
// This code is contributed by Mayank Tyagi
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。