Home > Mobile >  How to pass a struct array to a function
How to pass a struct array to a function

Time:03-17

I want to pass a struct array into a function, however, there's something wrong with how I'm passing it and I cant figure out what. I'll include the relevant code.

The Struct:

typedef struct fitbit
{
    char patient[10];

} FitbitData;

Main.c:

FitbitData* data = (FitbitData*)malloc(sizeof(data) * 1450);
count = storeToksInArray(line, count, data);

function:

 int storeToksInArray(char line[], int count, FitbitData* data[]) 
    {
    strcpy(data[count]->patient, strtok(line, ",")); //name
    puts(data[count]->patient); }

I've already tested my code and there aren't any problems with line or count. The array works fine in my main file, but once I pass it into the function I can't get it to store the data correctly. The strcpy and puts functions work fine in main as well, so I'm 90% sure it's how I'm passing the array into the function and then using it in the function. I can also use the strtok and puts functions fine by themselves in the function, but once I try storing the token in the array, it doesn't work.

Edit: I figured it out! I removed the brackets after FitbitData data[] to get FitbitData data and then change -> to .**

CodePudding user response:

int storeToksInArray(char line[], int count, FitbitData* data[])

The expression FitbitData* data[] means data is an array of pointers to FitbitData. You seem to be wanting instead a pointer to an array of FitbitData. But an array type is effectively a pointer, so you don't need to pass a pointer to it. Consider changing your function declaration to:

int storeToksInArray(char line[], int count, FitbitData data[])

CodePudding user response:

It appears that data is a FitbitData pointer, and yet your function is expecting an array of FitbitData pointers. Perhaps what you want is either:

int storeToksInArray(char line[], int count, FitbitData* data)

or

int storeToksInArray(char line[], int count, FitbitData data[])

Both are equivalent in this context, it's a question of which you prefer or which seems clearer to you. Personally, I prefer the first one.

  • Related