raymond
raymond

Reputation: 3

c programming language fixed size array

If I declare a function parameter as myfunc(char (*p) [10]) what is the correct syntax for returning said pointer p ?

char *myfunc(char (*p) [10]) {
    /* do something */
    return (*p);
}

compiles and appears to work but it doesn't look correct (i.e., it doesn't seem to suggest that the pointer returned necessarily is a pointer to an array of size 10).

Upvotes: 0

Views: 129

Answers (2)

Chef Gladiator
Chef Gladiator

Reputation: 1008

typedef is one of your friends. Declare the type alias pointer to your required array:

typedef char (* ptr_to_char_arr_10) [10];

Now use it for myfunc:

 ptr_to_char_arr_10  myfunc(ptr_to_char_arr_10 p) {
    /* do something */
     *p[0] = 42;
    return p;
}

And now use it to use myfunc:

int main ( void )
{
    char char_arr_10 [10] = {0};

    ptr_to_char_arr_10 arrp = myfunc(&char_arr_10) ;

    assert( *arrp[0] == 42 );

    return EXIT_SUCCESS ;
}

Godbolt

Pointer to the array is a powerful concept. For further inspiration perhaps see it here, used with Variably Modified Types and heap allocation.

Bonus

The question is actually titled: "c programming language fixed-size array". Arrays as function argument actually can be declared with a "fixed" size.

// "fixed " array argument declaration
static void  dbj_assign(
        char val_, 
        // run time size of the array arg.
        const int count_, 
        // array argument of a minimal required size
        char char_arr [static count_]
     ) 
    {
        /* char_arr can not be null here*/
        /* do something */
        char_arr[0] = val_;
    }  

That char_arr argument is also a Variably Modified Type (VMT), with minimal size required also declared. Usage is in the same Godbolt.

Upvotes: 1

Eric Postpischil
Eric Postpischil

Reputation: 222526

char x declares a character.

char x[10] declares an array of ten characters.

char (*x)[10] declares a pointer to an array of ten characters.

char (*x())[10] declares a function that returns a pointer to an array of ten characters.

char (*x(char (*p)[10]))[10] declares a function that takes a pointer to an array of ten characters and returns a pointer to an array of ten characters.

Upvotes: 3

Related Questions