String in function parameter

int main() { char *x = "HelloWorld"; char y[] = "HelloWorld"; x[0] = 'Z'; //y[0] = 'M'; return 0; } 

In the above program, HelloWorld will be in the read-only section (for example, in the row table). x will point to this section read-only, so trying to change these values ​​will be undefined.

But y will be allocated on the stack, and HelloWorld will be copied to this memory. so changing y will work fine. String literals: pointer versus char array

Here is my question:

In the following program, both char *arr and char arr[] raise a segmentation error if the contents are changed.

 void function(char arr[]) //void function(char *arr) { arr[0] = 'X'; } int main() { function("MyString"); return 0; } 
  • How does it differ in the context of a function parameter?
  • No memory will be allocated for function parameters?

Share your knowledge.

+7
source share
3 answers

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

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

The problem is the calling context. You have provided a string literal for the function; string literals cannot be changed; your function tried to change the string literal it gave; your program caused undefined behavior and crashed. All completely kosher.

Pay attention to string literals as if they were static const char literal[] = "string literal"; and did not try to modify them.

+17
source
 function("MyString"); 

looks like

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

"MyString" in both cases is a string literal, and in both cases the string cannot be changed.

 function("MyString"); 

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

+6
source

char * arr; above means that arr is a pointer to a character, and it can point to either a single character or a string of characters

& char arr []; the statement above implies that arr is a character string and can store as many characters as possible, or even one, but will always count on the character "\ 0", which makes it a string (for example, char arr [] = "a" is like char arr [] = {'a', '\ 0'})

But when used as parameters in the called function, the transmitted string stores character by character in formal arguments, without making any difference.

+1
source

All Articles