0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

考えてみれば当たり前なんだけどstrncmp(str1, str2, 0)は0文字分の比較 → 真

Posted at

string.hstrncmp(str1, str2, n) は、str1とstr2をn文字分比較してくれます。
当然 int n=0 なんて初期化して臨むといきなりやられる。

こんなのにハマるなんて。。くちおしや。。

test.c
# include <stdio.h>
# include <string.h>

int main(void)
{
  char* str1 = "ponta";
  char* str2 = "pontasan";
  char* str3 = "fuwafuwa";

  printf("strncmp(str1, str2, 7): %d\n", strncmp(str1, str2, 7) );
  printf("strncmp(str1, str2, 6): %d\n", strncmp(str1, str2, 6) );
  printf("strncmp(str1, str2, 5): %d\n", strncmp(str1, str2, 5) );
  printf("strncmp(str1, str2, 4): %d\n", strncmp(str1, str2, 4) );
  printf("strncmp(str1, str2, 3): %d\n", strncmp(str1, str2, 3) );

  printf("\n");

  printf("strncmp(str2, str3, 5): %d\n", strncmp(str2, str3, 5) );
  printf("strncmp(str2, str3, 0): %d\n", strncmp(str2, str3, 0) );

  return 4444;
}
a.out
strncmp(str1, str2, 7): -115
strncmp(str1, str2, 6): -115
strncmp(str1, str2, 5): 0
strncmp(str1, str2, 4): 0
strncmp(str1, str2, 3): 0

strncmp(str2, str3, 5): 10
strncmp(str2, str3, 0): 0
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?