C 指针段错误混淆

标签 c segmentation-fault

我正在学习指针并浏览此斯坦福 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 = &num;
    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/

相关文章:

c++ - OpenCV 4.2.0 FileStorage段错误

c - ubuntu 中的段错误

c - 你如何检测 C 中的 ctrl+D?

c - 了解 MIPS 汇编代码段

c - HTTP 请求被拒绝(3xx 4xx 响应)

将 char 数组的分段转换为 int

c - 当我尝试使用 realloc 将新行插入 2D-Array 时出现段错误

c - 段错误(核心转储)-我的代码出了什么问题

c - 如何增加每个循环中具有全局指针的数组大小

c - 如何修复 "Segmentation fault(core dumped)"?