【问题标题】:error: expected initializer before '*' token错误:“*”标记之前的预期初始化程序
【发布时间】:2017-06-04 23:00:57
【问题描述】:
#include <iostream>

using namespace std;

int** add(int** first, int** second);
int addAllElems(int** matrix);
int addAllElems(int** matrix);
void display(int** matrix);

int main()
{
    int first** = {{5,7,4}, {3,9,2}, {7,3,6}};
    int second** = {{3,7,2}, {6,2,6}, {3,5,8}};

    cout << "The first matrix is:" << endl;
    display(first);
    cout << endl;

    cout << "The second matrix is:" << endl;
    display(second);
    cout << endl;

    cout << "The sum of the two matrices is:" << endl;
    display(add(first, second));
    cout << endl;

    cout << "The sum of all elements of the first matrix is: "
        << addAllElems(first) << endl;
    cout << endl;

    return 0;
}

int** add(int** first, int** second) {
    int[][] sum = new int[3][3];
    for (int i = 0; i <= 2; i++) {
        for (int j = 0; j <= 2; j++) {
            sum[i][j] = first[i][j] + second[i][j];
        }
    }
    return sum;
}

int addAllElems(int** matrix) {
    int sumOfElems = 0;
    for (int i = 0; i <= 2; i++) {
        for (int j = 0; j <= 2; j++) {
            sumOfElems += matrix[i][j];
        }
    }
    return sumOfElems;
}

void display(int** matrix) {
    cout << "[" << endl;
    for (int i = 0; i <= 2; i++) {
        for (int j = 0; j <= 2; j++) {
            cout << matrix[i][j] << ", ";
        }
        cout << endl;
    }
    cout << "]" << endl;
}

谁能修复这个代码?

编译时出现这个错误:

 In function 'int main()':
12:14: error: expected initializer before '*' token
63:1: error: expected '}' at end of input

我认为问题出在我的数组声明上。 我认为问题出在我的数组声明中。 我认为问题出在我的数组声明中。 我认为问题出在我的数组声明上。

【问题讨论】:

  • 指针不是二维数组。
  • @Inyavic Sage 这个声明和初始化 int first** = {{5,7,4}, {3,9,2}, {7,3,6}}; (我认为您的意思是 int ** first 而不是 int first ** )是不正确的。一个标量对象可以用一个只有一个初始化器的花括号列表来初始化。

标签: c++ arrays multidimensional-array syntax-error


【解决方案1】:

首先,星星需要直接位于类型的右侧:

int** first;

那你需要用不同的方式初始化它:

int** first = new int*[3];
    for (int i = 0; i < 3; i++)
    {
        first[i] = new int[3];
    }
    first[0][0] = 5;
    first[0][7] = 7;
    // ...

【讨论】:

    猜你喜欢
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多