What exactly does & (p [* (i + j)]) do?

Executing the following code will print orld. What's going on here? What exactly is doing &(p[*(i + j)])?

#include <stdio.h>
char p[] = "HelloWorld";
int i[] = {2,1,3,5,6}, j = 4;

int main()
{
    printf(&(p[*(i + j)]));
    return 0;
}
+4
source share
6 answers

I will try to simplify it step by step

#include <stdio.h>
char p[] = "HelloWorld";
int i[] = {2,1,3,5,6}, j = 4;

int main()
{
    printf(&(p[*(i + j)]));
    return 0;
}

The first three lines are obvious:

  • p - an array of 10 characters
  • i - an array of 5 integers
  • j is an integer and has a value of 4

printf(&(p[*(i + j)]));

coincides with

printf(&(p[*(i + 4)]));

coincides with

printf(&(p[*([adress of first element of i] + 4)]));

coincides with

printf(&(p[*([adress of fourth element of i])]));

Now you should know what *addressgives you the value that is in address. So:

printf(&(p[6]));

Now that I think you fought. You must know:

  • arrays are basically nothing more than a piece of memory that is continuous. It is indicated by the starting address.
  • &something gives the address something

, "" HelloWorld orld. Python p[6:], C &p[6].

+2
char p[] = "HelloWorld";
int i[] = {2,1,3,5,6}, j = 4;

&(p[*(i + j)]) :

i - base address of array i. , i+4 address fifth element array i. *(i+j) 6. P[6] o W. &(p[*(i + j)]) &p[6]. , printf address of o, orld.

+3

:

1) . . :

int asd[5] = { 11, 12, 13, 14, 15 };    // <-- this is an array

/* the following is what it looks like in the memory:
11  12  13  14  15

the value of, for example, asd[4] is 15
the value of asd itself is the memory address of asd[0], the very first element
so the following is true:
asd == &asd[0]  */

2). , .. - , "HelloWorld" , , , '\0' , , ; . , "HelloWorld" .

3) asd[3], *(asd + 3) 3[asd] ; , asd + 3. asd, , / asd. int * asd, asd + 3 3 * sizeof ( int ) asd.

, , , &( p[ *(i + j) ] ):

    &( p[ *( i + j ) ] )
    &( p[ *( i + 4 ) ] )
    &( p[    i[4]    ] )
    &( p[      6     ] )    // This will return the address of `7th` element to the printf. 
     ( p      +      6 )    // A pointer to second 'o'

printf const char *, 'o', 'r', 'l', 'd', '\0', .

+3

: *(i+j) , i[j], 6. p[6] - p- 6.

, , < <24 > .

A char , 6- p, printf, "orld".

+1

&(p[*(i + j)])results in a lower expression, which is an address p[6]equal to j = 4.

&(p[*(i + j)]) == &(p[(i[j])]) == &(p[(i[4])]) == &(p[6]) == &p[6]

Yes, you can print using printfwithout a format specifier %s, since it takes strings as arguments.

+1
source

Read comments to explain

#include <stdio.h>
char p[] = "HelloWorld";
int i[] = {2,1,3,5,6}, j = 4;

int main()
{
    printf(&(p[*(i + j)])); //*(i+j) = i[j] => i[4]= 6
    // &(p[*(i + j)]) => place the pointer in memory block that his address p[6]
    // so printf print the string starting from the p[6] ie from 'o' => orld
    return 0;
}
0
source

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


All Articles