Comparing null-terminated string with a non null-terminated string in C

后端 未结 3 835
渐次进展
渐次进展 2021-01-25 02:46

The deserialization library (messagepack) I am using does not provide null-terminated strings. Instead, I get a pointer to the beginning of the string and a length. What is the

3条回答
  •  迷失自我
    2021-01-25 03:24

    int compare(char *one, size_t onelen, char *two, size_t twolen)
    {
    int dif;
    
      dif = memcmp(one, two, onelen < twolen ? onelen : twolen);
      if (dif) return dif;
    
      if (onelen == twolen) return 0;
      return onelen > twolen? 1 : -1;
    }
    

    usage:

    ...
    int result;
    char einz[4] = "einz"; // not terminated
    char *zwei = "einz";   // terminated
    
    result = compare(einz, sizeof einz, zwei, strlen(zwei));
    
    ...
    

提交回复
热议问题