[英]How do I compare two arrays of strings made from strdup() in C?
我想知道如何比較C 中的兩個字符串arrays。
這是我的代碼(比較時無法正常工作):
#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]);
}
}
}
}
我的比較方法有什么問題?
提前致謝,如果重復,對不起(我已經搜索但沒有找到類似的案例)。
編輯:我在splitted2
中沒有數據。 代碼已經修復
看起來您正在嘗試將字符串與 == 進行比較。 比較指針標識,這很少是你想要的。 嘗試這個:
if (!strcmp(splitted1[k], splitted2[m]))
strcmp()
是字符串比較 function。 如果它們相等,則返回 0,因此您需要。,實際的工作是返回負數、0 或正數,以便您可以按字節對字符串進行排序(如果 UTF-8 這也是代碼點)。 但通常你現在只是比較平等並使用不同的 function 進行排序(另一個主題)。
正如 IrAM 指出的那樣,您的原始副本缺少一些代碼,並且splitted2
中還沒有任何數據,因此會導致未定義的行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.