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

create value in function, then save pointer on value in global pointer array

本文关键字:指针 存在 全局 数组 保存 函数 创建 然后      更新时间:2023-10-16

我对c++比较陌生,也习惯了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; 
}

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

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。这似乎不是一个固有的问题。它离2,14e9太远了。第二版:输入值无关紧要。

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

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

或者只是:

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

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

编辑:在不添加原型的情况下将函数定义移动到main之上也可以,但最好使用原型。

在调用函数之前,编译器必须了解它。

因此,您可以重新排列函数定义,使test2排在第一位,test排在第二位,main排在最后,或者将test2test1的声明放在main:之前

void test2(int& j); // declaration
void test(int b);   // declaration
int main(int argc, char** argv) {
    // ...
}
void test(int b){ // definition
    // ...
}
void test2(int& j) { // definition
    // ...
}

这将揭示一个更严重的错误;您使用int*调用test2,但它需要int&。您可以通过将调用转换为test2(i);来解决此问题。


一旦您的函数被整齐地划分为声明和定义,就可以执行典型的C++源文件管理的下一步了:将声明放入头文件(通常为*.h*.hpp)中,并从包含main的实现文件(通常是*.cpp)中放入#include。然后为这两个函数定义再添加两个实现文件。在那里也添加相应的#include。别忘了在标题中加入警卫。

最后,分别编译这三个实现文件,并使用链接器从生成的三个对象文件中创建一个可执行文件。

在调用test2之前需要声明它。每个函数都需要在调用之前声明。

在main上面添加这些行来声明函数;

void test2(int& j);
void test2(int& j);
int main(){...}