Search code examples
cstructpass-by-referencedynamic-memory-allocationmember-access

how to initialize struct array members inside function by reference


im trying to make an array of struct and initialize struct array member, but I don't know how to access struct member, i used (st->ch)[t] = 'c'; and others similar syntax but i did not succeed.

best regards.

struct ST
{
    char ch;
};

bool init(ST* st, int num)
{
    st = (ST*)malloc(num * sizeof(ST));
    if (st == NULL) return false;

    for (int t = 0; t < num; t++) (st->ch)[t] = 'c';

    return true;
}

int main()
{
    ST* s = NULL;
    init(s, 2);

    putchar(s[1].ch);
}

Solution

  • You declared in main a pointer

    ST* s = NULL;
    

    that in C shall be declared like

    struct ST* s = NULL;
    

    because you declared the type specifier struct ST (that in C is not the same as just ST)

    struct ST
    {
        char ch;
    };
    

    that you are going to change within a function. To do that you have to pass the pointer to the function by reference. That is the function declaration will look at least like

    bool init( struct ST **st, int num );
    

    and the function is called like

    init( &s, 2);
    
    if ( s ) putchar( s[1].ch );
    

    The function itself can be defined like

    bool init( struct ST **st, int num )
    {
        *st = malloc( num * sizeof( struct ST ) );
    
        if ( *st )
        {
            for ( int i = 0; i < num; i++) ( *st )[i].ch = 'c';
        }
    
        return *st != NULL;
    }
    

    If you are using a C++ compiler then substitute this statement

        *st = malloc( num * sizeof( struct ST ) );
    

    for

        *st = ( struct ST * )malloc( num * sizeof( struct ST ) );
    

    When the array of structures will not be needed you should free the memory occupied by the array like

    free( s );