简体   繁体   English

在二维数组中出现“初始化值过多”错误

[英]getting "Too Many Initializer Values" error in 2D array

void Data::Paramters()
    
{
    for (int i = 0; i < I; i++)
    {
        mc[i] = new int[K];
        for (int k = 0; k < K; k++)
        {
            mc[i][k] = {{1, 0, 2, 3, 5},{ 4, 2, 2, 1, 3 }, { 4, 3, 4, 1, 3 }, { 3, 5, 6, 4, 2 } };
        }
    }
}

getting "Too Many Initializer Values" error in starting of { 4, 2, 2, 1, 3 } where I=5 and K=4在 I=5 和 K=4 的{ 4, 2, 2, 1, 3 } 开始时出现“太多初始化值”错误

The initializer is for a 4x5 2D matrix, so you should just write:初始值设定项用于 4x5 2D 矩阵,因此您应该只写:

enum { I = 4, K = 5 };

int mc[I][K] = { { 1, 0, 2, 3, 5 },
                 { 4, 2, 2, 1, 3 },
                 { 4, 3, 4, 1, 3 },
                 { 3, 5, 6, 4, 2 } };

The expression mc[i][k] has the type int .表达式mc[i][k]的类型为int It is not an array.它不是数组。

So this assignment statement所以这个赋值语句

mc[i][k] = {{1, 0, 2, 3, 5},{ 4, 2, 2, 1, 3 }, { 4, 3, 4, 1, 3 }, { 3, 5, 6, 4, 2 } };

does not make a sense.没有意义。

If K is a constant expression then you can allocate and initialize the two-dimensional array the following way如果K是常量表达式,则可以按以下方式分配和初始化二维数组

int ( *mc )[K] = new int[I][K]
{ 
    { 1, 0, 2, 3, 5 },
    { 4, 2, 2, 1, 3 }, 
    { 4, 3, 4, 1, 3 }, 
    { 3, 5, 6, 4, 2 } 
}; 

Here is a demonstration program.这是一个演示程序。

#include <iostream>

int main()
{
    const size_t K = 5;
    size_t I = 4;

    int ( *mc )[K] = new int[I][K]
    {
        { 1, 0, 2, 3, 5 },
        { 4, 2, 2, 1, 3 },
        { 4, 3, 4, 1, 3 },
        { 3, 5, 6, 4, 2 }
    };

    for ( size_t i = 0; i < I; i++ )
    {
        for (const auto &item : mc[i])
        {
            std::cout << item << ' ';
        }
        std::cout << '\n';
    }
}

The program output is程序 output 是

1 0 2 3 5
4 2 2 1 3
4 3 4 1 3
3 5 6 4 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM