I'd like to know the internal processing of this code.
char arr[] = "cat";
*arr = 'b';
printf("%s",arr);
Here in this code how is c in the array overridden by b?
Output : bat
If it helps to understand, *arr is the same as *(&arr[0])Note below, i.e., it refers to the value stored at index 0.
You are simply assigning a new value to it.
Graphically:
char arr[] = "cat";
is
+-------+--------+--------+--------+
| c | a | t | \0 |
+-------+--------+--------+--------+
arr[0] arr[1] arr[2] arr[3]
and, after
*arr = 'b'; // which is practically same as arr[0] = 'b';
is
+-------+--------+--------+--------+
| b | a | t | \0 |
+-------+--------+--------+--------+
arr[0] arr[1] arr[2] arr[3]
Note:
Quoting C11, chapter §6.3.2.1
Except when it is the operand of the
sizeofoperator, the_Alignofoperator, or the unary&operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. [...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With