Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of "p = (int[2]){*p};" line in C pointer?

From what I understood, I am passing the address of the variable a to the function int ffx1.

After that, what exactly does this line p = (int[2]){*p}; mean?

int ffx1(int * p)
{
    p = (int[2]){*p};
    return(p[1]);
}

int main()
{
    int a = 1;
    a = ffx1(&a);
    printf("%d", a);

   return 0;
}
like image 528
hago Avatar asked Oct 31 '17 17:10

hago


2 Answers

With int ffx1(int * p), p is a pointer to an int.

(int[2]){*p} is a compound literal defining an int array of 2. @BLUEPIXY This unnamed array we will call X[2]. Its first element have the value of *p, and the next element, being an int will be initialized to zero (§6.7.9 21 & 10 ) as it is not explicitly listed.

p = .... assigned the pointer p to a new value. In this case, the above array X[]is converted to the address of its first enrollment or &X[0].

return p[1] de-references p, returning the value in X[1] or 0.

like image 195
chux - Reinstate Monica Avatar answered Nov 12 '22 06:11

chux - Reinstate Monica


It is a pointer to compound literals.

C11-§6.5.2.5 Compound literals (p9):

EXAMPLE 2 In contrast, in

void f(void)
{
int *p;
/*...*/
p = (int [2]){*p};
/*...*/
}

p is assigned the address of the first element of an array of two ints, the first having the value previously pointed to by p and the second, zero. The expressions in this compound literal need not be constant. The unnamed object has automatic storage duration.

like image 9
msc Avatar answered Nov 12 '22 05:11

msc