Home > Software engineering >  Why does this not compare the characters?
Why does this not compare the characters?

Time:07-26

    #include <cs50.h>
    #include <stdio.h>
    #include <string.h>
    
    int main(int argc, string argv[])
    {
    
        int x = 0;
        string alphabet = ("abcdefghijklmnopqrstuvwxyz");
        int key_length = strlen(argv[1]);
    
        //checks if key is valid
        if (argc != 2)
        {
            printf("Usage: ./substitution key\n");
            return 1;
        }
        else if (key_length < 26)
        {
            printf("Key must contain 26 characters.\n");
            return 1;
        }
    
        //takes input from user
        string plaintext = ("Hello");
    
        for (int i = 0; i < 5; i  )
        {
            //loops until characters are the same
            while (strcmp(plaintext[i], alphabet[x]) != 0)
            {
                x  ;
            }
            //prints character
            printf("%s", argv[1][x]);
        }
    }

Error:

substitution.c:30:23: error: incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with & [-Werror,-Wint-conversion]
        while (strcmp(plaintext[i], alphabet[x]) != 0)
                      ^~~~~~~~~~~~
                      &
/usr/include/string.h:156:32: note: passing argument to parameter '__s1' here
extern int strcmp (const char *__s1, const char *__s2)
                               ^
fatal error: too many errors emitted, stopping now [-ferror-limit=]
2 errors generated.
make: *** [<builtin>: substitution] Error 1

CodePudding user response:

strcmp compares two character strings. To compare two characters, == can be used.

Remember: char* x = "..." defines a character array, x[n] is a character, and to C characters are just numbers, ergo plaintext[i] == alphabet[x] is valid.

You may want to use strchr() here to optimize this as there's no need to bash through byte by byte.

strchr(alphabet, plaintext[i])

CodePudding user response:

The error incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *' comes because you run strcmp not on a string (const char *) but on a string[index] (char).

You should either strcmp(string1, string2) [compare strings] or check string1[index] == string2[index] [compare char]

  •  Tags:  
  • c
  • Related