Reputation: 139
how to pass struct
type data using parameters to another function ? i have already create a global
struct
but i think i've miss something
#include <stdio.h>
#include <stdlib.h>
struct Stuff
{
int id;
String name[20];
}
// call another function
int myFunctionInsert(Stuff *stuff);
int main()
{
struct Stuff *stuff[20];
myFunctionInsert(*stuff);
}
int myFunctionInsert(Stuff *stuff)
{
int x;
for(x = 0; x < 25; x++){
stuff[x].id = x;
stuff[x].name = 'stuff';
}
}
so my purpose is when i already call the myFunctionInsert
, the struct
data same as i was input in that function.
for example, when i call myFunctionShow
(which is i'm not write in) the data show should be like this
id : 1
name : stuff
// until 25
when i tried my code above, i got an error
Unknown type name 'Stuff' (in line i call
myFunctionInsert(Stuff *stuff)
)
any help will be appreciated
thanks
Upvotes: 1
Views: 1332
Reputation: 6298
The problem is not only with lack of typedef
.
Also memory will be smashed since for(x = 0; x < 25; x++){
crosses the boundary of
struct Stuff *stuff[20];
Also stuff[x].name = 'stuff';
will not fly. You mean "stuff". Notice that there is no String
type in C language.
The working version of the program where size of the passed array of structures is specified may look like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct stuff
{
int id;
char name[20];
}Stuff;
// call another function
int myFunctionInsert(Stuff *stuff, int len);
int myFunctionInsert(Stuff *stuff,int len)
{
int x;
for(x = 0; x < len; x++){
stuff[x].id = x;
strcpy( stuff[x].name, "stuff");
printf("stuff %i id=%d name=%s\n", x, stuff[x].id, stuff[x].name );
}
}
int main()
{
Stuff sf[25];
myFunctionInsert(sf,5); // init 5 structures
return 0;
}
OUTPUT:
stuff 0 id=0 name=stuff
stuff 1 id=1 name=stuff
stuff 2 id=2 name=stuff
stuff 3 id=3 name=stuff
stuff 4 id=4 name=stuff
Upvotes: 3
Reputation: 2790
The type you defined is struct Stuff
not Stuff
. Hence:
// call another function
int myFunctionInsert(struct Stuff *stuff);
Alternatively use typedef
:
typedef struct Stuff
{
int id;
String name[20];
} Stuff;
Upvotes: 4