Stuffing the multidimensional array name and pointer arithmetic

I have this multidimensional array:

char marr[][3] = {{"abc"},{"def"}}; 

Now, if we meet the expression *marr by definition (ISO / IEC 9899: 1999), he says (and quotes)

If the operand is of type pointer to type, the result is of type type

and we have in this expression that marr splits into a pointer to its first element, which in this case is a pointer to an array, so we return a "type" array of size 3 when we have the expression * marr. So my question is: why when we do (* marr) + 1, we add 1 byte only to the address instead of 3, which is the size of the array.

Excuse my ignorance. I am not a very bright person, who sometimes get obsessed with such trivial things.

Thank you for your time.

+4
source share
2 answers

It adds one, since the type is char (1 byte). As well as:

 char *p = 0x00; ++p; /* is now 0x01 */ 

When dereferencing char [][] it will be used as char * in the expression.

To add 3, you first need to do arithmetic and then dereference:

 *(marr+1) 

You did:

 (*marr)+1 

what dereferencing first.

+1
source

The reason the increment (*marr) moves forward 1 byte is because *marr refers to char[3] , {"abc"} . If you do not already know:

 *marr == marr[0] == &marr[0][0] (*marr) + 1 == &marr[0][1] 

If you had only char single_array[3] = {"abc"}; how much would you expect single_array + 1 to move forward in memory? 1 byte to the right, not 3, since the type of this array of char and sizeof(char) is 1.

If you made *(marr + 1) , then you will refer to marr[1] , which you can expect from 3 bytes. marr + 1 is of type char[][3] , the size increment is sizeof(char[3]) .

The main difference between the two examples above is as follows:

  • The first is dereferenced to char[3] , and then increases, so the size of the increment is sizeof(char ).
  • The second increases the value of char[][3] , so the size of the increment is sizeof(char[3]) , and then dereferencing.
+3
source

Source: https://habr.com/ru/post/1384766/


All Articles