Question

I am trying to understanding the passing of string to a called function and modifying the elements of the array inside the called function.

void foo(char p[]){
  p[0] = 'a';
  printf("%s",p);
}
void main(){
  char p[] = "jkahsdkjs";
  p[0] = 'a';
  printf("%s",p);
  foo("fgfgf");
}

Above code returns an exception. I know that string in C is immutable, but would like to know what is there is difference between modifying in main and modifying the calling function. What happens in case of other date types?

Was it helpful?

Solution

I know that string in C is immutable

That's not true. The correct version is: modifying string literals in C are undefined behaviors.

In main(), you defined the string as:

char p[] = "jkahsdkjs";

which is a non-literal character array, so you can modify it. But what you passed to foo is "fgfgf", which is a string literal.

Change it to:

char str[] = "fgfgf";
foo(str);

would be fine.

OTHER TIPS

In the first case:

char p[] = "jkahsdkjs";

p is an array that is initialized with a copy of the string literal. Since you don't specify the size it will determined by the length of the string literal plus the null terminating character. This is covered in the draft C99 standard section 6.7.8 Initialization paragraph 14:

An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

in the second case:

foo("fgfgf");

you are attempting to modify a string literal which is undefined behavior, which means the behavior of program is unpredictable, and an exception is one possibility. From the C99 draft standard section 6.4.5 String literals paragraph 6 (emphasis mine):

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

The difference is in how you are initializing p[].

char p[] = "jkahsdkjs";

This initializas a writeable array called p, auto-sized to be large enough to contain your string and stored on the stack at runtime.

However, in the case of:

foo("fgfgf");

You are passing in a pointer to the actual string literal, which are usually enforced as read-only in most compilers.

What happens in case of other date types?

String literals are a very special case. Other data types, such as int, etc do not have an issue that is analogous to this, since they are stored strictly by value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top