Why is the function (char * array []) a valid function definition, but not (char (* array) [] in C?

I think this is because the first is an array of pointers to char, and the last is a pointer to an array of characters, and we need to correctly indicate the size of the object that its function definition points to, In the first;

function(char * p_array[])

the size of the indicated object is already included (its pointer to char), but the last

function(char (*p_array)[])

requires a p_array array size indicating as part of the p_array definition? I am at a stage that I have been thinking about this for too long and have just embarrassed myself, someone, please tell me if I am reasoning correctly.

+5
source share
4 answers

C, ++. :

char *x[]; // array of pointers to char
char (*y)[]; // pointer to array of char

, . :

char **x; // Changes to pointer to array of pointer to char
char (*y)[]; // No decay, since it NOT an array, it a pointer to an array

C, . (, ). ,

int valid_array[][5]; // Ok
int invalid_array[5][]; // Wrong

( ... ...)

int (*convoluted_array[][5])[][10];

catch,, catch , [] . , , . , :

void func(int (*x)[])
{
    x[2][5] = 900; // Error
}

, x[2] , x[0] x[1]. x[0] x[1] int [] - , . , , "" , int x[][] - . C. C,

  • .

    void func(int n, int x[])
    {
        x[2*n + 5] = 900;
    }
    
  • . , 2D-.

    void func(int *x[])
    {
        x[2][5] = 900;
    }
    
  • .

    void func(int x[][5])
    {
        x[2][5] = 900;
    }
    
  • ( C99, , , Microsoft).

    // There some funny syntax if you want 'x' before 'width'
    void func(int n, int x[][n])
    {
        x[2][5] = 900;
    }
    

. " " , , (++, Java, Python), (Common Lisp, Haskell, Fortran). , .

+14

. [], , *, , :

function(char **p_array);

. char (*)[], - . - :

char (*p_array)[];

, , ( ) - , . , [] a[i], *(a+i), . , , , :

void function(char (*p_array)[])
{
    printf("p_array = %p\n", (void *)p_array);
}

char, :

void function(char (*p_array)[])
{
    char (*p_a_10)[10] = p_array;

    puts(*p_a_10);
}

... :

void function(char (*p_array)[])
{
    puts(*p_array);
}

( : char *).

, *p_array , p_array[0] .

+3

,

(1) function(char * p_array[])

char **p_array; .. .

(2) function(char (*p_array)[])

, p_array char. , . , .

+2

Note:
The following answer was added when Q was tagged with C ++, and it responds in terms of C ++. With tags changed only to C, both of these examples are valid in C.

Yes, your reasoning is correct.
If you try to compile the error specified by the compiler, follow these steps:

parameter ‘p_array’ includes pointer to array of unknown bound ‘char []’

In the size of the C ++ array, you need to fix the compilation time. The C ++ standard prohibits variable array length (VLA). Some compilers support this as an extension, but this is not standard.

+2
source

All Articles