[英]Below program is terminating abnormally when comparing strings why?
我正在比较两个字符串数组,但是程序在比较了一些字符串后异常终止:
我的代码有什么问题?
int main()
{
int N,Q;
printf("Enter no. of strings:");
scanf("%d",&N);
char *a[N],*b[Q],k[50],*p;
int len;
//scanning first array of strings
for(int i=0;i<N;i++)
{
scanf("%s",k);
len=strlen(k);
p=(char*)malloc((len+1)*sizeof(char));
strcpy(p,k);
a[i]=p;
}
printf("no. of Query:");
scanf("%d",&Q);
//scanning second array of strings
for(int i=0;i<Q;i++)
{
scanf("%s",k);
len=strlen(k);
p=(char*)malloc((len+1)*sizeof(char));
strcpy(p,k);
b[i]=p;
}
***//comparing both the arrays of strings***
for(int i=0;i<Q;i++)
{
for(int j=0;j<N;j++)
{
int i=strcmp(a[j],b[i]);
printf("%d\t",i);
}
printf("\n");
}
return 0;
}
将strcmp的结果分配给不同的变量名而不是'i',因为“ i”是您的外部循环变量,但是b[i]
在堆栈中
for(int i=0;i<Q;i++)
{
for(int j=0;j<N;j++)
{
int i=strcmp(a[j],b[i]);
printf("%d\t",i);
}
printf("\n");
}
在b[Q]
的声明中, Q
被初始化-之后任何事情都可能发生。 您将至少需要移动b[]
的声明,直到分配Q
为止。
可能还有其他问题-这只是显而易见的问题。
您正在输入字符串的数量,但使用不正确。 您应该使用动态内存分配。 使用malloc
printf("Enter no. of strings:");
scanf("%d",&N);
和
char *a[N]
应该在哪里
a = malloc(sizeof(char*) * N);
并在返回之前将其释放以避免内存韭葱。 I am not sure that this is the problem but this can be a step in the right direction.
基于@Clifford的EDIT注释:C99标准允许这样做,因此,如果您的编译器支持C99,这不是问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.