小编Mar*_*k R的帖子

在“ for”循环初始化器中取消引用指针会产生分段错误

我在for循环中使用指针时遇到问题。在for循环初始化程序中,我取消引用int指针并将其值设置为“ 0”。当我在循环中使用该取消引用的指针时,出现了段错误,并且我不明白为什么。我正在使用Code :: Blocks和C GNU GCC编译器。

  1. 看着观察窗口,我可以看到在for循环过程中变量有一个随机数。

  2. 似乎已取消引用的指针在for循环期间丢失了作用域。

代码:

#include <stdio.h>

int main(void)
{
    int val = 0;
    int *p = NULL;
    int answer = 0;

    p = &val;

    *p = 1; // This dereferences and sets to one successfully

    for (int i=3, (*p)=0 ; i>=0; i--) // Here *p is a random number
    {
        printf("do stuff");
        (*p) += 1; // Here it causes a segmentation fault
    } …
Run Code Online (Sandbox Code Playgroud)

c pointers for-loop declaration

45
推荐指数
2
解决办法
1496
查看次数

标签 统计

c ×1

declaration ×1

for-loop ×1

pointers ×1