c语言中字符串和数字的组合不能正确比较
我试图用指针比较两个字符串。当我只输入字符串或数字时工作正常。但当我输入字符串和数字的组合时。尽管它们不同,但返回的两个字符串是相同的 例如: hello123和hello321都返回相同的值c语言中字符串和数字的组合不能正确比较,c,pointers,string-comparison,C,Pointers,String Comparison,我试图用指针比较两个字符串。当我只输入字符串或数字时工作正常。但当我输入字符串和数字的组合时。尽管它们不同,但返回的两个字符串是相同的 例如: hello123和hello321都返回相同的值 #include<stdio.h> void main() { char *i[10],*p[10],sum; int j,k=0; clrscr(); printf("enter the string\n"); gets(*i); prin
#include<stdio.h>
void main()
{
char *i[10],*p[10],sum;
int j,k=0;
clrscr();
printf("enter the string\n");
gets(*i);
printf("enter the string\n");
gets(*p);
for(j=0;*p[j]!=0;j++)
{
if(*p[j]!=*i[j])
{
k=1;
break;
}
}
if(k==0)
{
printf(" same");
}
else
{
printf("not same");
}
getch();
}
当你申报时
char *i[10],*p[10];
其中i和p展开为指向字符数组的指针。使用此选项,您无法比较单个字符串
尝试以下更改-
#include<stdio.h>
void main()
{
char i[10],p[10],sum;
int j,k=0;
char *x,*y;
printf("enter the string\n");
// gets(i);
fgets(i, sizeof i, stdin);
printf("enter the string\n");
// gets(p);
fgets(p, sizeof p, stdin);
x=i; y=p;
while(*x){
if(*x != *y){
k=1;
break;
}
x++; y++;
}
if(k==0)
{
printf(" same\n");
}
else
{
printf("not same\n");
}
}
char*i[10]不是字符串,而是未初始化指针的数组。因此,调用是未定义的行为。无论如何,使用gets本身就是个坏主意。你需要先解决这个问题。然后,使用调试器检查程序的状态。此外,main返回int,而不是void。移除所有的星星,你就可以开始了。是什么让你认为有一个10个指向字符的指针数组是正确的?这个数组可以工作,但我想用指针比较字符串。使用scanf读取用户的输入-不。不要。Ever.so是否有任何方法可以使用指针来比较字符串?@user2503585在这种情况下为什么需要显式指针?你可以做char*ip=i,*pp=p;并使用ip和pp指针而不是数组,但这是毫无意义的-数组已经隐式衰减为指向其第一个元素的指针。@user2503585有关获取用户输入的信息,请参阅我的编辑。gets和scanf本质上是危险的,应该改用FGET。
root@sathish1:~/My Docs/Programs# ./a.out
enter the string
hello
enter the string
hello
same
root@sathish1:~/My Docs/Programs# ./a.out
enter the string
hello123
enter the string
hello321
not same