使用数组下标时出现分段错误核心转储

问题描述 投票:0回答:2

我正在尝试实现一个相当基本的程序,但我得到了一个被转储的核心。对我做错了什么有什么想法吗?

#include <stdio.h>

int
main(void){


    char *number [] = {"one","two","three","four","five","six","seven","eigth","nine"};
    char *object [] = {"sf","sfe","sefg","efsef","seg","eshse","segeg","ryte","asrh","asegh"};

    for(int i=0;i<10;i++){

        printf("In this code %s\n this should %s\n work\n\n",number[i],object[i]);


    }


}
c segmentation-fault
2个回答
1
投票

您遇到了一个经典的“相差一”错误。您的“

number
”数组中的元素太少。
object
中有十个元素,但
number
中只有九个。


1
投票

Joe 说得对:你的循环从 0 到 9,即十个项目。你想要 0 到 8。

顺便说一句,这是一个真正常见的初学者错误。

图案是

for index = 0; while index is less than length; add one to index
© www.soinside.com 2019 - 2024. All rights reserved.