Mst137 Mst137 - 1 year ago 64
C Question

Passing an array of a structure between functions

I have a structure "Register" declared like this:

typedef struct {
int TypeID;
unsigned char InstrumentType[128];
unsigned char RegTag[128];
unsigned char Protocol[128];
int RegNum;
unsigned char RW[128];
unsigned char RegisterType[128];
unsigned char Signed[128];
unsigned char Inverted[128];
unsigned char DataType[128];
int Counts;
} Register;

I have an array of Registers called "Reg[9]" and want to create a function called 'TransferValues' to assign values to all the fields in the structure for each element of the array. Once the values are updated they will be outputted individually in
. How can I pass the array to and from this function?

Answer Source

In arrays decay to pointer when passed to function, so you can simply call the function passing your array, and that's it.

Little example using a pointer:

#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <inttypes.h>

typedef struct {
    int32_t TypeID;
    char InstrumentType[128];
} Register;

void func ( Register *reg, size_t n_regs )
    for (size_t i=0; i< n_regs; i++)
        reg[i].TypeID = (int32_t)(i);
        sprintf(reg[i].InstrumentType, "Instrument_%zu", i);

int main (void)
    Register Reg[9] = {{0}};

    func(Reg, sizeof(Reg)/sizeof(Reg[0]));

    for (size_t i=0; i<sizeof(Reg)/sizeof(Reg[0]); i++)
        printf ("Reg[%zu].TypeID = %"PRId32"\n", i, Reg[i].TypeID);
        printf ("Reg[%zu].InstrumentType = %s\n", i, Reg[i].InstrumentType);

As you can see you should also pass to the function you are going to write the size of passed array to be sure to not go out of bounds of passed array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download