I have a struggle understanding a syntax of pointers, for example, I have this code below:
void main(void)
{
char arr[][10] = {"It's", "wide", "and", "wonderful"};
printf("%c", (*arr)[3] - 1);
printf("%c", *arr[2] + 3);
}
I have no clue why it prints 'r' and 'd' like what's the whole process, I would kindly like an explanation.
This is obfuscation: code deliberately written to confuse.
*arr
gives the first item (array) in your 2D array. At index 3 you find 's'
. ASCII code for 's'
- 1 = 'r'
.
In *arr[2]
, the [] operator takes precedence, giving you the item at index 2 in your 2D array ("and"). *
gives the contents of the first item (character) in that array, 'a'
. ASCII code for 'a'
+ 3 = 'd'
.
(Please note that arithmetic on symbol table values is not portable code. Only the digits 0 to 9 are guaranteed by the C standard to be placed adjacently in the symbol table.)
I'll break up the expressions (*arr)[3] - 1
and *arr[2] + 3
in order of precedence.
Expression (*arr)[3] - 1
:
arr
→ {"It's", "wide", "and", "wonderful"}
(*arr)
→ "It's"
(*arr)[3]
→ 's'
(*arr)[3] - 1
→ 'r'
Notice here two things: *arr
is equivalent to arr[0]
, and you can perform arithmetic on a char
, operating on the numeric value representing the character.
Expression *arr[2] + 3
:
arr
→ {"It's", "wide", "and", "wonderful"}
arr[2]
→ "and"
*arr[2]
→ 'a'
*arr[2] + 3
→ 'd'
The news here is that arr[]
takes precedence over *arr
, that is why the parenthesis is important in the first expression.
void main(void)
{
char arr[][10] = {"It's", "wide", "and", "wonderful"};
printf("%c", (*arr)[3] - 1); // arr[0][3] == the 4th char of the 1st string - 1 = s - 1 = r
printf("%c", *arr[2] + 3); // arr[2][0] == the 1st char of the 3rd string + 3 = a + 3 = d
}
in first case (*arr)[3] - 1
in second case *arr[2]
:
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