You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编译含指针的C代码出现段错误:移除‘maximum = array’的原因咨询

为什么移除maximum = array会触发段错误?

先把完整代码贴出来方便咱们对照分析:

int main() { 
    long array[1000], *maximum, size, c, location = 1; 
    printf("Enter the number of elements in array\n"); 
    scanf("%ld", &size); 
    printf("Enter %ld integers\n", size); 
    for ( c = 0 ; c < size ; c++ ) 
        scanf("%ld", &array[c]); 
    maximum = array; 
    *maximum = *array; 
    for (c = 1; c < size; c++) { 
        if (*(array+c) > *maximum) { 
            *maximum = *(array+c); 
            location = c+1; 
        } 
    } 
    printf("Maximum element is present at location number %ld and it's value is %ld.\n", location, *maximum); 
    return 0; 
}

咱们直接抓问题的核心:

  • maximum是个未初始化的局部指针:在C语言里,局部变量(包括指针)如果没被显式赋值,会持有随机的内存地址,也就是咱们常说的「野指针」——指向的区域要么不属于当前程序,要么是受保护的内存,程序根本没权限读写。
  • 原来的maximum = array这句话,是把数组array的首地址塞给maximum,让它合法地指向数组的第一个元素。这时候maximum就有了一个程序完全有权操作的内存地址。
  • 一旦你删掉这条语句,maximum还是那个野指针。接下来执行*maximum = *array的时候,本质是在尝试往一个非法内存地址写数据。操作系统会立刻拦截这种越权操作,直接抛出segmentation fault(段错误)终止程序。

另外提一句:原代码里的*maximum = *array其实有点多余——因为maximum已经指向array[0]了,这行等于把array[0]的值再赋给自己,但它能安全执行的前提,完全是因为前面的maximum = array给指针找了个合法的“落脚点”。

内容的提问来源于stack exchange,提问作者Combospirit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:56:05