在C编程中查找多维数组中的元素

时间:2015-09-05 01:47:13

标签: c arrays

在尝试通过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;
}

但是,当我输入“Peter Paul John Mary”并尝试搜索时,它并没有返回“是 - 匹配索引位置: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;
        }
    }
}
}

1 个答案:

答案 0 :(得分:4)

您不想使用nameptr[row][col] == target,而是希望将其替换为strcmp(nameptr[row][col],target) == 0==比较指针(内存地址),strcmp比较字符串的实际值,并在匹配时返回0