Patrick Patrick - 2 months ago 27
C Question

Pass struct array to function

I want to assign a1 into ana[0], ana1 only inside the storeDataHere function.

Inside saveData function, just need to pass each data_array[0] to storeDataHere function.

#include <stdio.h>
#include <string.h>
struct Analysis{
int a;
int b[10];
};

struct Analysis ana[2];

void storeDataHere(void* res)
{
// initialize a1;
struct Analysis a1;
a1.a = 1;
memset(a1.b, 0, 10*sizeof(int));

for(int i=0; i<10; i++)
a1.b[i] = 1;


// store a1 into ana[0], ana[1];
struct Analysis temp = res;
temp = a1;

}

void saveData(void* data, size_t size)
{

struct Analysis *data_array = data;
// pass two struct elements to storeDataHere;
storeDataHere((void*)data_array[0]);
storeDataHere((void*)data_array[1]);
}



int main()
{
// pass struct array ana to saveData
saveData( (void*)ana, sizeof(ana[0]));

for(int i=0; i<2; i++)
{
printf("\n%d\n", ana[i].a);
for(int j=0; j<10; j++)
printf("%d", ana[i].b[j]);
}

return 0;
}


Here is the output with errors:

enter image description here

How to solve this if I keep this structure of function? (Not to change the function param)

Answer

See answer here:

https://repl.it/D2Cd

// use struct Analysis* instead of void*
//
void storeDataHere(struct Analysis* res)
{
    int i;
    // initialize a1;
    struct Analysis a1;

    a1.a = 1;
    // memset(a1.b, 0, 10*sizeof(int)); no need to memset cause you set later

    for (i = 0; i < 10; i++) 
    {
        a1.b[i] = 1;
    }

    // store a1 into ana[0], ana[1];
    *res = a1; // assign value of pointer res to a1 
}

// pass array struct to function
void saveData(struct Analysis data[])
{
    struct Analysis *data_array = data;
    // pass two struct elements to storeDataHere;
    storeDataHere(&data_array[0]);
    storeDataHere(&data_array[1]); // pass pointer of each element to StoreDataHere
}

See the link for more details. Happy coding!!

Comments