简体   繁体   中英

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. 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". Instead, it returned me with the No – no such name: -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 . == compares the pointers (memory addresses), strcmp compares the actual values of the strings, and returns 0 when they match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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