0

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 .**

1
  • 1
    what does FitbitData look like? If it has pointers and not arrays you will need to allocate them before copying e.g. patient Commented Mar 17, 2022 at 6:35

2 Answers 2

1
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[])
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.