Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Pointer within parentheses

Tags:

c++

pointers

I am a bit confused about this syntax.

void function ( float (*points)[2]); 

Is this declaring an array of float pointers? If so, why the following code returns an error:

void foo( float (*points)[2]) {}

float *p[2];
foo(p); // error

float (*p)[2];
foo(p); // okay

Why do you need the parentheses?

like image 501
Giuseppe Pes Avatar asked Feb 22 '16 11:02

Giuseppe Pes


Video Answer


2 Answers

float *p[2] defines an array of float*, with size 2.

float (*p)[2] defines a pointer to an array of float, with size 2:

int main(int argc, char* argv[])
{

    float* p[2];
    p[0] = new float(0.0);
    p[1] = new float(1.0);
    std::cout << *(p[0]) << " , " << *(p[1]) << "\n";

    float Q[2] = { 0.0, 1.0 };
    float(*q)[2] = &Q;
    std::cout << (*q)[0] << " , " << (*q)[1] << "\n";

    delete p[0];
    delete p[1];
}

Notice that if the sizes of Q and q doesn't match, you get an error:

float Q[3] = { 0.0, 1.0, 2.0 };
float(*q)[2] = &Q; //error C2440: 'initializing' : cannot convert from 'float (*)[3]' to 'float (*)[2]'
like image 113
Adi Levin Avatar answered Oct 19 '22 11:10

Adi Levin


This is a pointer to an array of two float values. Its practical purpose is an ability to pass a 2-D array with one dimension fixed to 2:

float data[][2] = {{1.2, 3.4}, {5.6, 7.8}, {9.1, 10.2}};
foo(data);

Typically a function like that would also take the overall size of the array.

Alternatively, a function like that could be used to allocate an array of two floats, and set the pointer to the result of allocation.

like image 21
Sergey Kalinichenko Avatar answered Oct 19 '22 12:10

Sergey Kalinichenko