2

I am writing a very simple function in C to check if a string is an absolute path or relative path. No matter what I try it is always returning false.

Here is what I have tried:

int isAbsolute(char *str){
    if(strcmp(str,"/")){
        return 1;
    }
    return 0;
}

and I call it like:

printf("%d\n", isAbsolute("/"));

which is returning false every time. Clearly I am missing something obvious but I haven't been able to figure it out...

CodySig
  • 174
  • 1
  • 4
  • 15
  • 4
    `strcmp` compares the whole string, so it will only return true if the string you're passing is "/". You can look at `strncmp` instead, or compare only one character (`if (str[0] == '/')`), instead of a string. – AntonH Sep 06 '17 at 16:41
  • @AntonH: Why not place this as an answer? – alk Sep 06 '17 at 16:45
  • @alk I was only going to comment why it wasn't working, but edited a solution in after. Put it as an answer now ... – AntonH Sep 06 '17 at 16:46
  • Ah wow ok thank you. I had tried this as well but I was using "/" instead of '/'. Thank you. Not sure why when I use "/" it tries to compare str[0] as a pointer and "/" as an int? – CodySig Sep 06 '17 at 16:59

5 Answers5

6

Don't have access to a compiler, but I think this will work because C-style strings are just arrays with a termination character:

int isAbsolute(const char *str){
    return (str[0] == '/');
}
Billy Ferguson
  • 1,429
  • 11
  • 23
3

As was pointed out, strcmp only matches if the strings being compared are of the same length.

To compare a single character at the front of the string, you can just do:

int isAbsolute(const char *str) {
  return (str[0] == '/');
}

If the prefix you are looking for is longer than one character, then this might help. I like Fred Foo's answer better than the one that got accepted (as did a majority of voters).

pat
  • 12,587
  • 1
  • 23
  • 52
3

strcmp compares the whole string, so your function will only return true if the string you're passing is "/".

You can look at strncmp instead:

if(strncmp(str,"/", 1)) ...

or compare only one character:

(if (str[0] == '/')) ...
AntonH
  • 6,359
  • 2
  • 30
  • 40
2

Similarly to strncmp you can use memcmp which has the number of bytes to compare as an argument:

int isAbsolute(const char *str){
    if (0 == memcmp(str, "/", 1){
         return 1;
    } else {
         return 0;
    }
}

Don't forget that return value $0$ means equality. In your code you return 0 in that case which is probably not as you intended.

Henno Brandsma
  • 2,116
  • 11
  • 12
0

Strcmp return value is zero on success case ,that's why it is not going to true

rohit
  • 39
  • 1
  • 8