Miles Nomas Miles Nomas - 28 days ago 7
C Question

How can I pass an array of structures to a function by reference?

#include <stdio.h>

void changeValues(struct ITEM *item[]);

struct ITEM
{
int number;
};

int main(void)
{
struct ITEM items[10];
for (int i = 0; i < 10; i++)
{
items[i].number = i;//initialize
printf("BEFORE:: %d\n", items[i].number);
}

changeValues(items);

for (int i = 0; i < 10; i++)
{
items[i].number = i;
printf("AFTER:: %d\n", items[i].number);
}

return 0;
}

void changeValues(struct ITEM *item[])
{
for (int i = 0; i < 10; i++)
item[i] -> number += 5;
}


I am trying to pass an array of structures to a function. I need to change the values of the structures members within the function by reference and not value. For some odd reason when I print the results after the function is called the values remain the same as they were prior to the function call.

Answer

In C you can't pass by reference (like C++). You can only pass by value, or pass by pointer.

In this case, it appears that you want to pass an array of struct to function changeValues. That's what you do in main. However, the prototype and implementation of changeValues you actually try to pass an array of pointer to struct ITEM.

One possible fix is to change the array of pointer to struct ITEM to just array of struct.

void changeValues(struct ITEM item[])
{
    for (int i = 0; i < 10; i++)
    {
        item[i].number += 5;
    }
}

EDIT: You actually had two other mistakes in your code:

1) The definition of struct ITEM need to be before changeValues prototype:

struct ITEM
{
    int number;
};

void changeValues(struct ITEM item[]);

2) In your main() you actually reset all value in changeValues - basically you invalidated everything done in that function:

for (int i = 0; i < 10; i++)
{
    items[i].number = i;   // <-- Remove this line as you are resetting the value again here
    printf("AFTER:: %d\n", items[i].number);
}

struct ITEM
{
    int number;
};

void changeValues(struct ITEM item[]);


int main(void)
{
    struct ITEM items[10];
    for (int i = 0; i < 10; i++)
    {
        items[i].number = i;//initialize
        printf("BEFORE:: %d\n", items[i].number);
    }

    changeValues(items);

    for (int i = 0; i < 10; i++)
    {
        // items[i].number = i;   // <-- Remove this line as you are resetting the value again here
        printf("AFTER:: %d\n", items[i].number);
    }

    return 0;
}

void changeValues(struct ITEM items[])
{
    for (int i = 0; i < 10; i++)
    {
        items[i].number += 5;
    }
}
Comments