Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding array manipulation pointers syntax in C

Tags:

c

pointers

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.

like image 287
Oh123 Avatar asked Feb 10 '20 10:02

Oh123


4 Answers

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.)

like image 112
Lundin Avatar answered Nov 14 '22 00:11

Lundin


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.

like image 29
lvella Avatar answered Nov 14 '22 01:11

lvella


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
}
like image 2
Eraklon Avatar answered Nov 14 '22 01:11

Eraklon


in first case (*arr)[3] - 1

  • (*arr) gives us pointer to the first element of array: "It's"
  • (*arr)[3] gives us fourth element of "It's" which is: 's'
  • subtracting 1 from 's' gives us 'r'

in second case *arr[2]:

  • arr[2] gives us pointer to the third element of array: "and"
  • *arr[2] gives us first character of "and" which is 'a'
  • adding 3 to 'a' gives us 'd'
like image 2
ioseb Avatar answered Nov 13 '22 23:11

ioseb