简体   繁体   中英

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

The initializer is for a 4x5 2D matrix, so you should just write:

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 . 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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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