c++ - 在函数中创建值,然后将指针保存在全局指针数组中的值上

标签 c++ arrays pointers

我对 C++ 比较陌生,但习惯了 Java(我更喜欢 Java)。 我这里有一些指针问题。我创建了一个最小程序来模拟更复杂程序的行为。

这是代码:

void test (int);
void test2(int*);

int* global [5];    //Array of int-pointer

int main(int argc, char** argv) {
    int z = 3;
    int y = 5;      
    cin >> z;       // get some number
    global[0] = &y; // global 0 points on y

    test(z);        // the corpus delicti

    //just printing stuff
    cout << global[0]<<endl;   //target address in pointer
    cout << &global[0]<<endl;  //address of pointer
    cout << *global[0]<<endl;  //target of pointer

    return 0; //whatever
}


//function doing random stuff and calling test2
void test (int b){
    int i = b*b;
    test2(&i);
    return;
}

//test2 called by test puts the address of int i (defined in test) into global[0]
void test2(int* j){
   global[0]= j; 
}

棘手的部分是 test2。我将我在测试中创建的变量的地址放入全局指针数组中。不幸的是,这个程序给我一个编译器错误:

main.cpp: In function 'int test(int)':
main.cpp:42:20: error: 'test2' was not declared in this scope
     return test2(&i);
                    ^

我在这里找不到任何范围问题。我尝试将 test 的 int i 更改为全局变量,但没有帮助,所以我想,这不是原因。

编辑:它现在可以编译,但为 cin = 20 提供了错误的值。 *global[0] 应该是 400,但是是 2130567168。这似乎不是 int/uint 的问题。离2,14e9太远了。 Edit2:输入值无关紧要。

最佳答案

'test2' was not declared in this scope 这是因为编译器不知道 test2 是什么。您需要在 main 之上添加一个函数原型(prototype)。

void test (int b);
void test2(int& j);

或者只是:

void test (int);
void test2(int&);

因为此时编译器只需要知道参数的类型而不是它们的名字。

编辑:将函数定义移动到 main 之上而不添加原型(prototype)也可以,但最好使用原型(prototype)。

关于c++ - 在函数中创建值,然后将指针保存在全局指针数组中的值上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36210169/

相关文章:

arrays - 如何在 Groovy 中迭代数组?

c - 移动指针以便以不同的顺序打印

c++ - 数组指针数组的析构函数

c++ - NULL 指针的取消引用是否也等于 NULL?

c++ - CUDA & VS2010问题

c++ - 如何确定商店的实际发展水平,例如C++ 与 C?

Python - 在列中打印二维数组

c++ - 在哪里可以找到 boost::fusion 文章、示例、指南、教程?

尝试呈现 SDL_Texture : Invalid texture 时出现 C++ SDL2 错误

javascript - 通过选择一个值来打印列表 - Javascript