String in function parameter

后端 未结 3 995
时光说笑
时光说笑 2020-12-15 08:41
int main()
{
        char *x = \"HelloWorld\";
        char y[] = \"HelloWorld\";

        x[0] = \'Z\';
        //y[0] = \'M\';

        return 0;
}
相关标签:
3条回答
  • 2020-12-15 08:51

    char *arr; above statement implies that arr is a character pointer and it can point to either one character or strings of character

    & char arr[]; above statement implies that arr is strings of character and can store as many characters as possible or even one but will always count on '\0' character hence making it a string ( e.g. char arr[]= "a" is similar to char arr[]={'a','\0'} )

    But when used as parameters in called function, the string passed is stored character by character in formal arguments making no difference.

    0 讨论(0)
  • 2020-12-15 08:59
    function("MyString");
    

    is similar to

    char *s = "MyString";
    function(s);
    

    "MyString" is in both cases a string literal and in both cases the string is unmodifiable.

    function("MyString");
    

    passes the address of a string literal to function as an argument.

    0 讨论(0)
  • 2020-12-15 09:12

    Inside the function parameter list, char arr[] is absolutely equivalent to char *arr, so the pair of definitions and the pair of declarations are equivalent.

    void function(char arr[]) { ... }
    void function(char *arr)  { ... }
    
    void function(char arr[]);
    void function(char *arr);
    

    The issue is the calling context. You provided a string literal to the function; string literals may not be modified; your function attempted to modify the string literal it was given; your program invoked undefined behaviour and crashed. All completely kosher.

    Treat string literals as if they were static const char literal[] = "string literal"; and do not attempt to modify them.

    0 讨论(0)
提交回复
热议问题