C代码核心转储

时间:2017-12-09 20:21:56

标签: c string core

#include<stdio.h>
int main(){
int i,j,c[10],max=0,min=100;
char s[10][100];

for(i=0;i<10;i++)
    scanf("%s",&s[i][i*10]);
    c[i]=0;

for(i=0;i<10;i++)
    for(j=0;s[i][j]!="\0";j++)
        c[i]++;
for(i=0;i<10;i++){
    if(c[i]>max)
        max=c[i];
    else if(c[i]<max)
        min=c[i];
        }
printf("%d",max-min);

return(0);
}

这段代码应该从用户那里得到10个名字并找到每个名字的长度并减去最长的最短名称并且代码编译正确但是当我运行它时,它说核心倾倒了为什么?

1 个答案:

答案 0 :(得分:0)

第一件事,为什么s[i][i*10]在扫描字符串时,你没有按字符扫描char,你是逐字符串扫描,所以替换这个

for(i=0;i<10;i++)
    scanf("%s",&s[i][i*10]);//core dumped reason is this line

for(i=0;i<10;i++)
    scanf("%s",&s[i]);

第二件事s[i][j]!="\0"记住s [i] [j]是字符而不是字符串&amp;您正在与字符串"\0"进行比较,而是使用'\0'它应该是

 for(j=0;s[i][j]!='\0';j++)

编辑:

#include<stdio.h>
int main(){
        int i,j,c[10];
        char s[10][100];
        for(i=0;i<10;i++){
                scanf("%s",s[i]); //here you arestoring 10 string into s
                c[i]=0; //initializing whole c with 0, better you can do in beginning like int c[10] ={0} 
        }

        for(i=0;i<10;i++){
                //for(j=0;j<100;j++){ //this won't work because we don't know what is 50th character, can't guarantee always NULL
                for(j=0;s[i][j]!='\0';j++){
                        if(s[i][j]!='\0'){
                                c[i]++;
                                //c[i]++;//in c[0] storing length of first string, then in c[1] storing length of 2nd string  & so on
                        }
                }
        //      printf("length = %d \n",c[i]);
        }
        printf("%d\n",c[2]);// print the length of 3rd string(assume 3string washello.. it will print 5 
        return 0;
}

我希望你现在清楚。