Marco Marco - 2 months ago 10
C Question

Pass structure array to function as a `reference` using pointers

I am trying to send a structure array as reference, but for some reason I cannot get it to work, as value it is able to pass it but not as reference (&)

This is my code:

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

struct mystruct {
char line[10];
};

void func(struct mystruct record[])
{
printf ("YES, there is a record like %s\n", record[0].line);
}

int main()
{
struct mystruct record[1];
strcpy(record[0].line,"TEST0");
func(record);
return 0;
}


I thought that only by calling the function func(&record) and changing the func function arguments as "struct mystruct *record[]" it was going to work... but it didn't.

Any help please.

Answer

I think you've got your pointers and references concepts mixed up.

func(&record) would pass the address of the variable record and not a reference.

passing pointers

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

struct mystruct {
    char line[10];
};

void func(struct mystruct * record)
{
    printf ("YES, there is a record like %s\n", record[0].line);
    // OR
    printf ("YES, there is a record like %s\n", record->line);
}

int main()
{
    struct mystruct record[1];
    strcpy(record[0].line,"TEST0");
    func(record); // or func(&record[0])
    return 0;
}

if you must pass a reference, try this

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

struct mystruct {
    char line[10];
};

void func(struct mystruct & record)
{
    printf ("YES, there is a record like %s\n", record.line);
}

int main()
{
    struct mystruct record[1];
    strcpy(record[0].line,"TEST0");
    func(record[0]);
    return 0;
}

Update

To address the comment(s) below,

  • references are not available in pure C, available only in C++
  • the 'fault' in the original code was a struct mystruct record[] should have been struct mystruct & record