Link to home
Create AccountLog in
Avatar of Jax Logan
Jax Logan

asked on

Pass an array of pointers to structs by reference to a function (C)

Experts,

how do I pass a fixed-size array of pointers to structs by reference to a function in C?

Below is the code of what I'm trying to do but I'm getting the error:
cannot convert from 'MyStruct *' to 'MyStruct'

Thanks!


#include "stdafx.h"
#include <stdio.h>
#include <string.h>

#define MAX_SIZE_MY_STRUCTS 2

typedef struct _MyStruct
{
    char name[40];
    int index;
} MyStruct;

int populateStructs(MyStruct **my_struct_list)
{
    int i = 0;

    for (i=0; i < MAX_SIZE_MY_STRUCTS; i++) {
        (* my_struct_list[i]) = (MyStruct *)malloc(sizeof(MyStruct));
        strcpy(* my_struct_list[i]->name, "blah blah");
        (* my_struct_list[i])->index = i;
    }

    return 0;
}


int _tmain(int argc, _TCHAR* argv[])
{
    int i = 0;
    MyStruct *my_struct_list[MAX_SIZE_MY_STRUCTS] = {0};

    populateStructs(& my_struct_list);

    for (i=0; i < MAX_SIZE_MY_STRUCTS; i++) {
        printf("Name: %s\n",my_struct_list[i]->name);
        printf("Index: %d\n",my_struct_list[i]->index);
    }

	return 0;
}

Open in new window

Avatar of evilrix
evilrix
Flag of United Kingdom of Great Britain and Northern Ireland image

Change the function prototype to this..

int populateStructs(MyStruct *(*my_struct_list)[MAX_SIZE_MY_STRUCTS])

Open in new window

You will also need to change line 19 to this

(* my_struct_list[i]) = (MyStruct *)malloc(sizeof(MyStruct));

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of AriMc
AriMc
Flag of Finland image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of Jax Logan
Jax Logan

ASKER

Thanks!