Search code examples
carraysdynamicstructcalloc

Dynamically allocating an array of structs in Main and then having a function assign to it


I'm building a server for a project and I need to store a bunch of values in a ordered way. I've been searching for hours and I haven't figured out how.

I built a struct as follows:

struct WHITEBOARD{
    int line;
    char type;
    int bytes;
    char string[1024];  
} *Server;

Then in my main function I want to dynamically allocate memory to create an array of structs WHITEBOARD to a size of [argv[1]] (eventually). I would like to use calloc and in my research I have found the following:

void main()
{
    struct whiteboard (*Server) = (struct whiteboard*) calloc(10, sizeof(*Server));
    (*Server).line = 2;
    printf("Test: %d\n",(*Server).line);
}

This works but I can't seem to find out how to turn Server into an array of structs so that I can reference (*Server)[1].line and assign to this heap bound variable from a function. Which I intend to do as follows.

char* doThing(struct whiteboard Server)
{
    (*Server)[1].line = 4;
    return;
}

And be able to printf the newly bound variable from main.

This might be a dumb question, but any help would be awesome. Thanks!


Solution

  • struct WHITEBOARD{
        int line;
        char type;
        int bytes;
        char string[1024];  
    } *Server;
    

    You have a variable (a pointer to struct WHITEBOARD) called Server at global scope, thus, you don't need to redeclare-it inside main nor inside your function parameters, also note that you are misusing the dereference operator (*), to access the element 1 in (*Server)[1].line = 4; just use Server[1].line = 4;

    void doThing(void) /* Changed, you promise to return a pointer to char but you return nothing */
    {
        Server[1].line = 4;
    }
    
    int main(void) /* void main is not a valid signature */
    {
        Server = calloc(10, sizeof(*Server)); /* Don't cast calloc */
    
        Server[1].line = 2;
        doThing();
        printf("Test: %d\n", Server[1].line);
        free(Server);
    }