Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'd like to know what is internally happening in this code?

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
like image 840
chetan vamshi Avatar asked Nov 27 '25 18:11

chetan vamshi


1 Answers

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 sizeof operator, the _Alignof operator, 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. [...]

like image 168
Sourav Ghosh Avatar answered Nov 29 '25 11:11

Sourav Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!