How do I compare two arrays of strings made from strdup() in C?

Viewed 82

I'm wondering how do I compare two arrays of strings in C.

This is my code (not working properly when comparing):

#include <stdio.h>
#include <string.h>

int main() {
    char *splitted1[64];
    char *splitted2[64];
    int w1 = 0, w2 = 0;

    char ph1[64];
    fgets(ph1, 64, stdin);
    strtok(ph1, "\n");

    char ph2[64];
    fgets(ph2, 64, stdin);
    strtok(ph2, "\n");

    char spl[] = " ";
    char *ptr1 = strtok(ph1, spl);
    while (ptr1 != NULL) {
        splitted1[w1] = strdup(ptr1);
        ptr1 = strtok(NULL, spl);
        w1++;
    }
    char *ptr2 = strtok(ph2, spl);
    while (ptr2 != NULL) {
        splitted2[w2] = strdup(ptr2);
        ptr2 = strtok(NULL, spl);
        w2++;
    }

    // HERE I TRY TO COMPARE
    for (int k = 0; k < w1; k++) {
        for (int m = 0; m < w2; m++) {
            if (splitted1[k] == splitted2[m]) {
                printf("%s is on both arrays\n", splitted1[k]);
            }
        }
    }
}

What's wrong with my comparison method?

Thanks in advance and sorry if duplicated (I already search but didn't find a similar case).

EDIT: I didn't have data in splitted2. Code already fixed

1 Answers

It looks like you're trying to compare strings with ==. That compares for pointer identity, which is rarely what you want. Try this:

if (!strcmp(splitted1[k], splitted2[m]))

strcmp() is the string comparison function. It returns 0 if they're equal, so you need the !. It's actual job is to return negative, 0, or positive so you can sort strings by byte (if UTF-8 this is also codepoint), but usually you're just comparing for equality these days and using a different function to sort (another topic).

As IrAM points out, your original copy was missing some code and didn't have any data in splitted2 yet so that would have lead to undefined behavior.

Related