在函数中创建值,然后将指针保存在全局指针数组中的值上
create value in function, then save pointer on value in global pointer array
我对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
排在最后,或者将test2
和test1
的声明放在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(){...}
- 使用指针在存在特征库的情况下动态分配 c++ 中的矩阵
- 构造函数 (C++) 中的 char 指针参数存在问题
- C++为什么我的指针选择排序中存在分段错误?
- 迭代时将指向differents类型的指针保存在std::向量中
- 如果模板中存在成员函数指针,如何获取该指针
- 指向类成员函数的指针中存在类型转换错误
- 一个对象的两个指针.删除了一个指针,对象仍然存在
- 是否存在将长整型转换为指针有效的情况
- C ++如何创建一个即使对象被覆盖也会持续存在的指针?
- 指向派生作品的基本指针,即使派生对象不存在
- 这个危险指针示例是否因为 ABA 问题而存在缺陷?
- 指向可能不存在的对象的指针向量
- 如果存在任何循环关系,我应该假设弱指针使用吗?
- 带有功能指针的Typedef:函数不存在
- 即使在返回值之前释放后,数据仍在指针中仍然存在
- C++尝试删除不存在的指针
- 如何使用shared_ptr确保指针的存在
- 构造函数中指针到指针的默认值存在问题
- 指向类的指针存在问题
- 时间指针存在吗?