accessing a value in return struct - c

if you have a function that returns a struct, is it then possible to access on of the internal values in struct that is returned, without having to handling the whole struct.
The code could look something like this;
struct myStruct
{
int value1;
int value2;
};
myStruct functionReturningStruct(void);
....
value2 = functionReturningStruct().value2
if it's possible in anyway, how?

Why don't you test?
#include <stdio.h>
struct myStruct
{
int value1;
int value2;
};
struct myStruct functionReturningStruct(void)
{
return (struct myStruct){10, 20};
}
int main(void)
{
int value = functionReturningStruct().value2;
printf("%d", value);
return 0;
}

It's possible.
Implementations I found use an implicit first argument of functionReturningStruct() which points to the structure, that is temporary allocated by the compiler on call point.
Indeed, it is equivalent to
{
struct myStruct __temp_myStruct;
__actual_functionReturningStruct(&__temp_myStruct);
value2 = __temp_myStruct.value2;
}

Related

Dynamic allocation of union of structs

I am trying to create a union of 2 structs (dfp and affine) and want to allocate them dynamically. I am getting errors in creating particular struct array inside union. Am I declaring union in right way?
#include <stdio.h>
#include <stdlib.h>
struct{
int fp;
}dfp;
struct{
int scale;
int zp;
}affine;
union{
struct dfp *df;
struct affine *af;
}quant;
struct member{
int total;
union quant arr;
};
int main(void) {
// your code goes here
struct member* ptr;
ptr = (struct member *)malloc(sizeof(struct member));
ptr->total = 2;
int type = 0;
if(!type){
ptr->arr->df = (struct dfp*)malloc(ptr->total*sizeof(struct dfp)); //error
for(int i=0;i<2;i++){
ptr->arr->df->fp[i] = 10;
}
}
else{
ptr->arr->af = (struct affine*)malloc(ptr->total*sizeof(struct affine)); //error
for(int i=0;i<2;i++){
ptr->arr->af->scale[i] = 10;
ptr->arr->af->zp[i] = 20;
}
}
return 0;
}
Most issues have already been pointed out by others separately. This is my attempt at writing a complete answer with explanations and advice.
First off, please check your exact compiler warnings and errors. These are your best help in resolving these kind of issues.
The program does not contain a union of structs, but a union of pointers to structs.
The program's definitions are not correct. Taking dfp as an example. This, struct { int fp; } dfp;, defines an anonymous struct with the the variable name dfp. The name of the struct should go before the struct declaration list, e.g. struct dfp { int fp; };. See here or see the C standard specifications.
Judging by the code in main, the member variables of the structs should be arrays of size 2 instead of single ints.
The operator -> is for "member access using a pointer". Since arr is not a pointer, use a dot (.) to access its members. See here.
Dynamically allocated memory must be free'd, or else the program will have one or more memory leaks.
Here is the full code with all mentioned corrections:
#include <stdio.h>
#include <stdlib.h>
struct dfp {
int fp[2];
};
struct affine {
int scale[2];
int zp[2];
};
union quant {
struct dfp *df;
struct affine *af;
};
struct member {
int total;
union quant arr;
};
int main(void) {
struct member* ptr;
ptr = (struct member *)malloc(sizeof(struct member));
ptr->total = 2;
int type = 0;
if(!type) {
ptr->arr.df = (struct dfp*)malloc(ptr->total*sizeof(struct dfp));
for(int i=0;i<2;i++){
ptr->arr.df->fp[i] = 10;
}
}
else {
ptr->arr.af = (struct affine*)malloc(ptr->total*sizeof(struct affine));
for(int i=0;i<2;i++){
ptr->arr.af->scale[i] = 10;
ptr->arr.af->zp[i] = 20;
}
}
if(!type) {
free(ptr->arr.df);
}
else {
free(ptr->arr.af);
}
free(ptr);
}
Correct the struct definition as below:
struct dfp {
int fp;
};
struct affine{
int scale;
int zp;
};

How to declare a function pointer in a struct, which the function that pointer points includes that struct in its body?

I tried to search quite a lot but I couldn't find exactly what I was looking for.
For example:
struct A {
int something;
void(*function_ptr)(void);
function_ptr = function;
}
void function(void) {
struct A sth;
}
As you can see, I cannot define the function before struct since it contains that struct in its body, but when I define the struct before, I can't point to that function since it hasn't been declared yet.
You probably want something like this:
#include <stdio.h>
struct A {
int something;
void(*function_ptr)(void);
};
void function(void) {
struct A sth;
// possibly use sth somewhere here
printf("Hello I'm in function\n");
}
int main()
{
struct A a;
a.function_ptr = function;
a.function_ptr();
}
or
int main()
{
struct A a = {0 , function }; // a.something = 0; a.function_ptr = function;
a.function_ptr();
}
or even something like this:
struct A* NewstructA()
{
struct A* newstruct = malloc(sizeof(*newstruct));
newstruct->function_ptr = function;
}
int main()
{
struct A* a = NewstructA();
(a->function_ptr)();
}

struct in c with an attribute that is a pointer to the same struct

i need to create a struct with an attribute that is a pointer to the same struct.
i'm trying this solution but not work:
typedef struct
{
int number;
void *other;
}mystruct;
extern mystruct first[];
extern mystruct second[];
mystruct first[] = {{1,NULL},{2,second}};
mystruct second[] = {{3,NULL},{4,first}};
mystruct *wrap;
wrap = (mystruct *)first[1].other;
int main(void){
printf("%d\n",first[0].number);
printf("%d\n",second[0].number);
printf("%d\n",wrap[1].number);
}
can someone help me?
best regards and thankyou
In C, you can name the struct before using it and typdefing it:
typedef struct mystruct_
{
int number;
struct mystruct_ *other;
} mystruct
I'm not entirely sure but are you looking for some sort of linked-lists or precisely speak Self Referential structure
struct list {
int something;
struct list *use_this_to_point_to_similar_type;
};
Here is another good reference what-is-self-referencing-structure-in-c
just a little bit simplification, and moving few instructions here and there, below code is a loosely written example of possibly what you are looking forward to achieve
#include<stdio.h>
struct mystruct
{
int number;
struct mystruct *other;
};
struct mystruct first[] = {{1,NULL},{2,NULL}};
struct mystruct second[] = {{3,NULL},{4,NULL}};
struct mystruct *wrap;
int main(void)
{
first[1].other = second;
second[1].other = first;
wrap = first[1].other;
printf("%d\n",first[0].number);
printf("%d\n",second[0].number);
printf("%d\n",wrap[1].number);
return 0;
}
your first and second don't need to be extern as they are allocated within your program. you can declare and init. var prior to the main. but the rest you must move into the main function:
int main(void){
wrap = (first[1].other);
printf("%d\n",first[0].number);
printf("%d\n",first[1].number);
printf("%d\n",second[0].number);
printf("%d\n",wrap[1].number);
return 0;}

Preferred allocation of nested structs

Is it preferable to dynamically allocate the 'inner' structs in a nested hierarchy? If the parent struct is dynamically allocated, does it even matter? Why/how does it matter? Just trying to build my understanding of implications of different, seemingly contradictory, ways memory is dealt with in a code base I'm dealing with.
For example, what are the benefits of:
struct Foo_type {
int i;
}; typedef struct Foo_type Foo;
struct Bar_type {
Foo f;
}; typedef struct Bar_type Bar;
int main() {
Bar* b = malloc(sizeof(Bar));
/* yada yada yada */
free(b);
return 0;
}
As opposed to:
struct Foo_type {
int i;
}; typedef struct Foo_type Foo;
struct Bar_type {
Foo* f;
}; typedef struct Bar_type Bar;
int main() {
Bar* b = malloc(sizeof(Bar));
b->f = malloc(sizeof(Foo));
/* yada yada yada */
free(b->f);
free(b);
return 0;
}
Are they equivalent/different?
As an added to #AndersK. answer, the first method (non dynamic) is preferred when we want to emulate inheritance, declaring the base struct inside the derived struct and casting the derived as base:
#include <stdio.h>
#include <stdlib.h>
struct foo {
int i;
};
struct bar {
struct foo f;
};
static void func(struct foo *f, int i)
{
f->i = i;
}
int main(void)
{
struct bar *b = malloc(sizeof(*b));
func((struct foo *)b, 1);
printf("%d\n", b->f.i);
return 0;
}
In case one, the struct is contained in one memory allocation block, so you can memcpy it and need only one free for freeing it.
In case two you occupy two memory blocks not necessarily beside each other so you will have additional hassle of keeping track of those two blocks.
If you start having more pointers and members in Bar_type you will increase the complexity of copying an instance of the type.

how to access the struct?

struct result {
int number;
int length;
};
struct result findLongestSeq(int intarray[], int size) {
result->number // undefined symbol
}
how to access the struct result inside the function findLongestSeq?
thanks
struct result {
int number;
int length;
};
struct result findLongestSeq(int intarray[], int size) {
struct result result;
result.number = 0;
result.length = 42;
return result;
}
If you are dealing with struct result foo then you access its members via foo.number.
If however you are dealing with a pointer to foo (struct result *foo) then you access its members via foo->number.
If you were to manually allocate your result struct via
struct result *result = (struct result *)malloc(sizeof (struct result));
Then you'd have to access its members via result->number (and would be responsible for freeing it once not used anymore).
Further more I'd rather use this for the sake of better readability:
typedef struct {
int number;
int length;
} ResultStruct;
This way you can then use ResultStruct result; instead of redundant and verbose struct result result;.
You have to keep in mind that by simply typing
struct result {
int number;
int length;
};
you only define how a struct with name result actually looks like, i.e. of what parts it is made up. This is a general definition, but you have variable of that type yet.
To access values of this struct you have to create a variable by
struct result myResult;
or however you want to call it. At this point you are able to access the members of this struct with myResult.number

Resources