search

Home  >  Q&A  >  body text

c++ - strcmp参数为char**,也能正常运行?

strcmp 函数库中的声明:

int __cdecl strcmp (
        const char * src,
        const char * dst
        )
#include<string.h>
#include<stdio.h>
 
int main( void )
{
      char *s1 = "abcdkkkd";
      char *s2 = "oefjeofjefo";
  
      printf( "%d", strcmp( &s1, &s2 ) );
  
      return 0;
}

程序为什么会正常运行?

迷茫迷茫2820 days ago715

reply all(4)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 14:25:29

    int strcmp( const char *lhs, const char *rhs );
    Function declaration, c99 is slightly different from c11, but it does not affect it.

    What is passed in is a pointer. Even if a string variable is passed in, it is still an address.

    compares the strings starting from the pointer address to the null character .

    Regarding your question, actually 比较的并不是你列出的两个字符串, 而是地址开始的字符串, maybe you will think that this address is not a string at the beginning, then C will search further in the memory until it encounters an empty string.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 14:25:29

    I tried it on vs2015 and got an error: "The actual parameter of type char* is incompatible with the formal parameter of type const char"

    reply
    0
  • PHPz

    PHPz2017-04-17 14:25:29

    I failed to compile. Tip error: cannot convert 'const char**' to 'const char*' for argument '1' to 'int strcmp(const char*, const char*)'. But you, the poster, the parameter passed in is not the address of that string! What you are passing in is the address of the variable. s1 and &s1 are different!

    reply
    0
  • 迷茫

    迷茫2017-04-17 14:25:29

    The Gcc compilation result is as follows:
    strcmp.c:9:5: warning: passing argument 1 of 'strcmp' from incompatible pointer type [enabled by default]
    You only passed the compilation because it was passed in All are addresses, so only a warning is reported, but the actual running result is still wrong.

    reply
    0
  • Cancelreply