我正在学习指针并浏览此斯坦福 PDF 中的示例 Stanford Pointers Guide
我决定使用他们的示例编写一些代码,以便更好地处理正在发生的事情。我正在处理 PDF 的第 21 页。
当我运行代码时,出现段错误,因此我知道我正在尝试访问不属于我的内存,但我不明白哪里出了问题。
这是我编写的代码:
#include <stdio.h>
#include <stdlib.h>
// function prototypes
void C();
void B();
void main(){
int *worthRef;
int num = 42;
worthRef = #
B(*worthRef);
}
// Takes value of interest by reference and adds 2
void C(int* worthRef){
*worthRef = *worthRef + 2;
printf("num = %d", &worthRef);
}
// adds 1 to value of interest then calls C()
void B(int* worthRef){
*worthRef = *worthRef + 1; // add 1 to worthRef as before
C(worthRef); // NOTE: no & required. We already have a pointer to
// the value of interest, so it can be
// passed through directly
}
最佳答案
// function prototypes
void C();
void B();
该评论是谎言。这些是没有原型(prototype)的函数声明(这是此代码中问题的一部分)。
B(*worthRef);
此行使用 int
调用 B
。 (给定声明 int *worthRef
,*worthRef
的类型为 int
。)
void B(int* worthRef){
但是这里 B
期望获得一个指向 int
的指针,这就是错误:您在需要指针的地方传递了一个数字。
要解决此问题,请将 main
中的调用更改为 B(worthRef)
(或 B(&num)
),然后更改
printf("num = %d", &worthRef);
至
printf("num = %d\n", *worthRef);
<小时/>
如果您在函数声明中包含原型(prototype),那么编译器会警告您有关该问题的信息(可能):
// function prototypes
void C(int *);
void B(int *);
关于C 指针段错误混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39057297/