Passing a string literal as a function parameter defined as a pointer

前端 未结 6 941
南旧
南旧 2021-02-05 20:19

I am reading the chapter on arrays and pointers in Kernighan and Richie\'s The C Programming Language.

They give the example:

/* strlen:  return         


        
6条回答
  •  [愿得一人]
    2021-02-05 20:44

    char str[] = "Hello, world";
    strlen(str);
    

    string in C are array of characters with terminating NULL ('\0'), that mean it should be in the memory some where.

    so what is the difference of sending a stored string as above and sending it directly as below

    strlen("Hello, World");
    

    The answer is both are same, but where the string is stored and how it's handled, here comes the compiler and stack.

    The compiler at compile time pushes the string in to stack and send the starting address (char*) in the stack, the calling function sees a pointer and access the string.

    The compiler also add codes after exist form the function to restore the stack in the correct place thus deleting the temporary string created Note: the above is implementation dependent of the compiler, but most of the compiler works this way

提交回复
热议问题