比较字符串与strcmp崩溃
我正在试验指针和字符串。在下面的代码中,所有内容都经过测试(您可以自己编译和运行),但当我试图使用 strcmp。代码在代码块中运行时没有警告。你能指出我的错误导致程序崩溃吗比较字符串与strcmp崩溃,c,string,generics,pointers,C,String,Generics,Pointers,我正在试验指针和字符串。在下面的代码中,所有内容都经过测试(您可以自己编译和运行),但当我试图使用 strcmp。代码在代码块中运行时没有警告。你能指出我的错误导致程序崩溃吗 #include<stdio.h> #include<stdlib.h> #include<string.h> int main() { int choice,x=7,k,q,cmp,j=0,i=0,N; cha
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int choice,x=7,k,q,cmp,j=0,i=0,N;
char v[5],str[80],c[5];
char *B[11][2]=
{"-----","0",
".----","1",
"..---","2",
"...--","3",
"....-","4",
".....","5",
"-....","6",
"--...","7",
"---..","8",
"----.","9",
NULL,NULL};
printf("Give a stream");
if(gets(str)) printf("%s\n",str);
fflush(stdin);
i=0;
while(str[i])
{
q=0;
j=i+1;
while(q%5!=0)
{
v[j]=str[j];
puts(v);
j++;
q++;
}
printf("Hello");
for(k=0; k<11; k++)
{
strcpy(c,B[k][0]);
printf("%s",c);
x=strcmp(v,c);
//Problem:
printf("%d",c);
if(x==0) printf("hi");
}
i=i+1;
j++;
}
}
#包括
#包括
#包括
int main()
{
整数选择,x=7,k,q,cmp,j=0,i=0,N;
charv[5],str[80],c[5];
char*B[11][2]=
{"-----","0",
".----","1",
"..---","2",
"...--","3",
"....-","4",
".....","5",
"-....","6",
"--...","7",
"---..","8",
"----.","9",
NULL,NULL};
printf(“给出一条流”);
如果(获取(str))printf(“%s\n”,str);
fflush(stdin);
i=0;
while(str[i])
{
q=0;
j=i+1;
而(q%5!=0)
{
v[j]=str[j];
出售(v);
j++;
q++;
}
printf(“你好”);
对于(k=0;k您正在执行的操作:
strcpy(c,B[k][0]);
现在c
声明为:
char c[5];
和B[k][0]
有5个字符。由于您希望c
是以NUL结尾的字符数组,因此必须有空间容纳NUL字符,并使用strncpy
您没有用数据填充v
。条件while(q%5!=0)
在输入时为false,因为q==0
。这使得v
未初始化,即包含垃圾。当k=10时,此程序将转储,因为B[10][0]=NULL。strcpy(char*dest,const char*src)将在src=NULL时转储。fflush(stdin);
是未定义的行为。这听起来像是学习如何使用调试器的时候了……这不一定能解决问题,但v[6]、c[6]和v[5]=c[5]='\0';将是必需的。C中的数组从0开始。因此,我在0-4中放置了5个字符,然后在位置5处放置一个NULL。@alex777:在大小为5的数组中没有第5个位置。