[英]Finding an element in multi dimensional array in C Programming
当我尝试在C编程中循环通过多维数组时,我遇到了一些问题。 预期的输出应该是这样的:
Enter no. of names: 4
Enter 4 names: Peter Paul John Mary
Enter target name: John
Yes - matched at index location: 2
Enter no. of names: 5
Enter 5 names: Peter Paul John Mary Vincent
Enter target name: Jane
No – no such name: -1
这是我的代码:
int main()
{
char nameptr[SIZE][80];
char t[40];
int i, result, size;
printf("Enter no. of names: ");
scanf("%d", &size);
printf("Enter %d names: ", size);
for (i = 0; i<size; i++)
scanf("%s", nameptr[i]);
getc(stdin);
printf("\nEnter target name: ");
gets(t);
result = findTarget(t, nameptr, size);
if (result != -1)
printf("Yes - matched at index location: %d\n", result);
else
printf("No - no such name: -1\n");
return 0;
}
int findTarget(char *target, char nameptr[SIZE][80], int size)
{
int row, col;
for (row = 0; row < SIZE; row++) {
for (col = 0; col < 80; col++) {
if (nameptr[row][col] == target) {
return col;
}
}
}
return -1;
}
然而,当我进入“彼得保罗约翰玛丽”并试图搜索时,它并没有返回“是 - 匹配索引位置:2”。 相反,它给我带来了No - no这样的名字:-1。 所以我在想我的代码中哪一部分出了问题。 有任何想法吗?
提前致谢。
修改部分
int findTarget(char *target, char nameptr[SIZE][80], int size)
{
int row, col;
for (row = 0; row < size; row++) {
for (col = 0; col < size; col++) {
if (strcmp(nameptr[row]+col, target)) {
return row;
break;
}
else {
return -1;
}
}
}
}
你不想使用nameptr[row][col] == target
,你想用strcmp(nameptr[row][col],target) == 0
替换它。 ==
比较指针(内存地址), strcmp
比较字符串的实际值,并在匹配时返回0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.