search

Home  >  Q&A  >  body text

c++ - strcmp

char a[2] = { '1','2' };
printf("%d", strcmp(a, "12"));

结果为 1

一个没有结束符,一个有结束符,为什么没有的比有的大?

迷茫迷茫2767 days ago635

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-04-17 15:05:10

    Char is generally regarded as an unsigned integer, a[2] is a random value, and there are only two situations: greater than 0 and equal to 0.

    Most of the time, a[2] is greater than '

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 15:05:10

    Similar to the previous question - that question, my answer was trampled by the crowd - strings are strings, and character arrays are character arrays. The strcmp function requires you to pass in a string, because only strings have

    char a[] = {'1', '2', 'rrreee'};
    printf("%d", strcmp(a, "12"));

    The result you get is not actually 1, but a random value. Because the strcmp function does not know the length of

    , it performs an out-of-bounds access to memory. a

    reply
    0
  • Cancelreply