Expected 'double **', but the argument is of type 'double (*) [2]'

I came across this weird behavior in C.

This code gives me a compilation warning:

expected 'double **' but argument is of type 'double (*)[2]'

What is the problem? Is the doubling array a double pointer, right?

By the way, if I send the array itself, the destination does not affect the values, and I do not know why.

#include <stdio.h>

void set1(double **x)
{
    (*x)[0] = (*x)[1] =1.0;
}

int main()
{
    double x[2];
    set1(&x);
    printf("%d\n%d\n",x[0],x[1]);
}
+4
source share
3 answers

For starters, in accordance with the C standard, the main function without parameters should be declared as

int main( void )

To output type objects, doubleyou should use at least the conversion specifier %finstead %d. Otherwise, the function printfhas undefined behavior.

Now about pointers.

T, T - , ,

T x;

T *

, , T.

#include <stdio.h>

void set1( T *x )
{
    //...
}


int main(void) 
{
    T x;

    set1( &x ) ;

    // ...

    return 0;
}

, T . T ?

:

typedef double T[2];

, typedef , .

#include <stdio.h>

typedef double T[2];

void set1( T *x )
{
    //...
}


int main(void) 
{
    T x;

    set1( &x ) ;

    // ...

    return 0;
}

, , &x ?

double ( *x )[2]. , double **, . .

,

#include <stdio.h>

void set1( double ( *x )[2] )
{
    (*x)[0] = (*x)[1] = 1.0;
}


int main(void) 
{
    double x[2];

    set1( &x ) ;

    printf( "%f\n%f\n", x[0] , x[1] );

    return 0;
}

, double **, ,

#include <stdio.h>

void set1( double **x )
{
    (*x)[0] = (*x)[1] = 1.0;
}


int main(void) 
{
    double x[2];
    double *p = x;

    set1( &p ) ;

    printf( "%f\n%f\n", x[0] , x[1] );

    return 0;
}

p double * double ** .

double *, .

#include <stdio.h>

void set1( double *x )
{
    x[0] = x[1] = 1.0;
}

int main(void) 
{
    double x[2];

    set1( x ) ;

    printf( "%f\n%f\n", x[0] , x[1] );

    return 0;
}
+4

& x x .  x , , . :

void set1(double *x)
{
    x[0] = x[1] =1.0;
}

int main()
{
    double x[2];
    set1(x);
    printf("%d\n%d\n",x[0],x[1]);
}

, , 2.

+2

There is no pointer syntax at all. You can simplify the code as follows:

#include <stdio.h>

void set1(double x[2])
{
    x[0] = x[1] = 1.0;
}

int main(void)
{
    double x[2];
    set1(x);
    printf("%f\n%f\n", x[0], x[1]);
}
+1
source

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


All Articles