Search code examples
cstringcharstrcmp

I can't access a char as a string


I have the following bit of code:

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

char values[] = {"abcde"};

int main(int argc, char *argv[])
{
    printf("%d\n", strcmp(&values[0], argv[1]));
    return EXIT_SUCCESS;
}

I compile and launch this way:

$ gcc main.c -o main
$ ./main a
98

The result of strcmpis 98, so the values are not the same. When I replace &values[0] by "a" in the code, I see that they are the same (strcmp output is equal to 0).

So is there a way to access values[0] as a string ? I guess that I need to somehow specify \0 at the end in order for the char to be used as a string, but I can't find a way.


Solution

  • The reason is that values[0] is not followed by a null-byte, so you end up comparing "abcde" with "a", which is not what you want. You can instead allocate a two char array that has a nullbyte:

    char mystr[2] = {values[0]}; // rest of the array is zeroed (null bytes)
    printf("%d\n", strcmp(mystr, argv[1]));