Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding an element in multi dimensional array in C Programming

Tags:

arrays

c

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;
        }
    }
}
}
like image 550
BlackMamba Avatar asked May 18 '26 19:05

BlackMamba


1 Answers

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.

like image 127
F. Stephen Q Avatar answered May 21 '26 16:05

F. Stephen Q



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!