Reputation: 313
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:
How to solve this if I keep this structure of function? (Not to change the function param)
Upvotes: 0
Views: 441
Reputation: 6171
See answer here:
// 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!!
Upvotes: 2
Reputation: 56479
You're trying to assign a pointer to an object, that's impossible, to have a copy you should:
// Copy values
struct Analysis temp = *((struct Analysis*)res);
// or
// Copy pointer
struct Analysis *temp = res;
Next problem is, passing elements of data_array
such as data_array[0]
to the function (according to your code), you must pass whole structure:
storeDataHere((void*)data_array);
Upvotes: 1
Reputation: 13924
Change (you need to cast void pointer and then dereference):
struct Analysis temp = res;
to
struct Analysis temp = *((struct Analysis *)res);
Another correction (cast and pass the correct type):
storeDataHere((void*)data_array);
Upvotes: 1