The Awesome Egg
The Awesome Egg

Reputation: 57

C - Pass struct by reference

I am trying to pass a structure by reference in C so that I can modify the values from within the function. This is the code I have so far, but it produces some warnings and one error.

main.c

#include <stdio.h>
#include "myfunctions.h"
#include "structures.h"

int main(int argc, char const *argv[] {

    struct MyStruct data;

    data.value = 6;

    printf("Before change: %d\n", data.value);

    changeData(data);

    printf("After change: %d\n", data.value);

}

myfunctions.c

#include "structures.h"

void changeData(MyStruct data) {
    data.value = 7;
}

myfunctions.h

#ifndef MyStruct
#define MyStruct

void changeData(MyStruct data);

#endif

structures.h

typedef struct {

    int value;

} MyStruct;

Errors Produced

In file included from main.c:2:0:
myfunctions.h:4:1: warning: parameter names (without types) in function declaration
 void changeData(MyStruct data);
 ^
In file included from main.c:3:0:
structures.h:5:1: warning: unnamed struct/union that defines no instances
 } MyStruct;
 ^
main.c: In function ‘main’:
main.c:9:5: error: ‘data’ undeclared (first use in this function)
     data.value = 6;
     ^
main.c:9:5: note: each undeclared identifier is reported only once for each function it appears in

Upvotes: 0

Views: 2634

Answers (2)

user3629249
user3629249

Reputation: 16540

applying all my comments and elimination of the unnecessary 'typedef', and placing it all in one file ( Note: there is no problem with extracting the various files), results in the following code:

#ifndef STRUCTURES_H
#define STRUCTURES_H

struct MyStruct
{
    int value;
};
#endif // STRUCTURES_H



#ifndef MYFUNCTIONS_H
#define MYFUNCTIONS_H

void changeData( struct MyStruct *data);

#endif // MYFUNCTIONS_H





#include <stdio.h>
//#include "myfunctions.h"
//#include "structures.h"

int main( void )
{
    struct MyStruct data;

    data.value = 6;

    printf("Before change: %d\n", data.value);

    changeData(&data);

    printf("After change: %d\n", data.value);
} // end function: main



//#include "structures.h"

void changeData( struct MyStruct *data)
{
    data->value = 7;
} // end function: changeData

which cleanly compiles and does do the desired operation

Upvotes: 0

melpomene
melpomene

Reputation: 85767

That's all caused by

#define MyStruct

With this line, you've defined MyStruct as a macro that expands to nothing. I.e. you've effectively removed all occurrences of MyStruct in the following code, which is why the compiler is so confused about seeing things like

typedef struct {

    int value;

} ;

or

void changeData( data);

To fix this, use

#ifndef MYFUNCTIONS_H_
#define MYFUNCTIONS_H_

instead. (This is the reason why we use ALL_UPPERCASE names for macros: To avoid accidental name clashes with normal identifiers.)

Upvotes: 6

Related Questions