I want to return a structure from a function instead of declaring the structure at the beginning. Can I do that? example:
// begin code
/*
should I declare struct here? I prefer to defining
in the function because I may not use that function depending on situation. Am I violating the scope of the structure?
*/
// function declaration
struct *ret(int a, int b);
main()
{
// do something on struct elements. e.g.
printf("%d\n", ret.value);
}
struct *ret(int, int)
{
typedef struct {
int value;
int index;
} s1;
/* or can I use struct
struct s1 {
int value;
int index;
};
*/
struct s1 ret;
ret.value = a;
ret.index = b;
return ret;
}
// end code
Or what if I use this code?
struct s1 {
int value;
int index;
}
// is this declaration correct?
struct *ret(int a, int b);
main()
{
struct s1 s;
// do something on struct s
printf("%d\n",s.value);
}
struct *ret(int a, int b)
{
struct s.value = a;
struct s.index = b;
}
// end code
If both of them are not correct, please tell me the correct way to return and pass a structure. Any small sample is good help. Thx.
// begin code
/*
should I declare struct here? I prefer to defining
in the function because I may not use that function depending on situation. Am I violating the scope of the structure?
*/
// function declaration
struct *ret(int a, int b);
main()
{
// do something on struct elements. e.g.
printf("%d\n", ret.value);
}
struct *ret(int, int)
{
typedef struct {
int value;
int index;
} s1;
/* or can I use struct
struct s1 {
int value;
int index;
};
*/
struct s1 ret;
ret.value = a;
ret.index = b;
return ret;
}
// end code
Or what if I use this code?
struct s1 {
int value;
int index;
}
// is this declaration correct?
struct *ret(int a, int b);
main()
{
struct s1 s;
// do something on struct s
printf("%d\n",s.value);
}
struct *ret(int a, int b)
{
struct s.value = a;
struct s.index = b;
}
// end code
If both of them are not correct, please tell me the correct way to return and pass a structure. Any small sample is good help. Thx.