-2

As you can see at followed sample, I am comparing words those inside lyric variable and I want to get count's unique word but result returns 0. Although there are 3 similar words as you can see in result, it doesn't enter into if block. What can cause this problem?

You can test through this application quickly.

Source

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

int main(int argc, char* argv[]) {

    char lyric[] ="lorem ipsum is printing\nlorem ipsum is letters";
    int i = 0, j = 0, k = 0, y = 0, l = 0, s = 0;

    s = sizeof(lyric)/sizeof(char);

    for(k; k<s; ++k)
    {
        if(lyric[k] == ' ')
            ++l;

        if(lyric[k] == '\n')
            ++l;
    }

    char *row;
    char *temp[l];

    row = strtok (lyric," \n");

    while (row != NULL)
    {
        temp[i++] = row;
        row = strtok (NULL, " \n");
    }

    for (i=0;i<l; ++i){
        for (j=(i+1);j<l; ++j){

            printf("%s == %s\n", temp[i], temp[j]);
            if(temp[i] == temp[j]){
                y++;
            }
        }
    }

    printf("Unique word count : %d",y);

    return 0;
}

Result

lorem == ipsum
lorem == is
lorem == printing
lorem == lorem
lorem == ipsum
lorem == is
ipsum == is
ipsum == printing
ipsum == lorem
ipsum == ipsum
ipsum == is
is == printing
is == lorem
is == ipsum
is == is
printing == lorem
printing == ipsum
printing == is
lorem == ipsum
lorem == is
ipsum == is

Unique word count : 0
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Goran Zooferic
  • 371
  • 8
  • 23

2 Answers2

4

In your code,

temp[i] == temp[j]

is not going to work as expected as the operands are pointers and what you want is to compare the contents of the memory pointed by the pointers, not the pointers themselves.

You need to use strcmp() to perform the comparisons.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

The problem here is that your comparison involves two pointers i.e. temp[i] and temp[j] are nothing but pointers pointing to a memory What you need to compare is the value pointed by those pointers you can do that by dereferencing the pointers using asterisk (*) operator i.e (*temp[i]) and (*temp[j]) or if you do not want to do it manually then use strcmp as mentioned. Refer this C String -- Using Equality Operator == for comparing two strings for equality

Community
  • 1
  • 1
Avinash Sharma
  • 111
  • 1
  • 11