PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 5, 2022

[FIXED] how to initialize struct array members inside function by reference

 July 05, 2022     c, dynamic-memory-allocation, member-access, pass-by-reference, struct     No comments   

Issue

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 );


Answered By - Vlad from Moscow
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing