简体   繁体   中英

Pass struct array to function

I want to assign a1 into ana[0], ana 1 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)

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!!

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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM