简体   繁体   English

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

[英]Finding an element in multi dimensional array in C Programming

I was having some problem when trying to loop thru multi-dimensional array in C programming. 当我尝试在C编程中循环通过多维数组时,我遇到了一些问题。 The expected output should be in this way: 预期的输出应该是这样的:

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 

And here is my code: 这是我的代码:

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;
}

However, when I entered "Peter Paul John Mary" and trying to search , it does not return me with the "Yes - matched at index location: 2". 然而,当我进入“彼得保罗约翰玛丽”并试图搜索时,它并没有返回“是 - 匹配索引位置:2”。 Instead, it returned me with the No – no such name: -1. 相反,它给我带来了No - no这样的名字:-1。 So I was thinking which part of my code went wrong. 所以我在想我的代码中哪一部分出了问题。 Any ideas? 有任何想法吗?

Thanks in advance. 提前致谢。

Modified portion 修改部分

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;
        }
    }
}
}

You don't want to use nameptr[row][col] == target , you want to replace it with strcmp(nameptr[row][col],target) == 0 . 你不想使用nameptr[row][col] == target ,你想用strcmp(nameptr[row][col],target) == 0替换它。 == compares the pointers (memory addresses), strcmp compares the actual values of the strings, and returns 0 when they match. ==比较指针(内存地址), strcmp比较字符串的实际值,并在匹配时返回0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM