How to use struct within an union, within a struct in C? - c

i am currently having a lot of struggle with a, for me personally, very complex structure
struct crypto_tfm
{
uint32_t crt_flags;
union
{
struct ablkcipher_tfm ablkcipher;
struct aead_tfm aead;
struct blkcipher_tfm blkcipher;
struct cipher_tfm cipher;
struct hash_tfm hash;
struct compress_tfm compress;
struct rng_tfm rng;
} crt_u;
void (*exit)(struct crypto_tfm *tfm);
struct crypto_alg *crt_alg;
void *crt_ctx[] CRYPTO_MINALIGN_ATTR;
};
I completely have no idea how to use this struct. so basicly i am completely lost with this
the function using this expects a struct crypto_tfm *tfm
first idea is the following:
struct crypto_tfm *new_tfm()
{
struct crypto_tfm *tfm = malloc(sizeof(struct crypto_tfm));
tfm -> crt_flags = 0;
tfm -> crt_u.
}
but i dont know how to get further,
the given structs within the union are also using another structs. kinda too complicated for me right now

This is untested, but should be a good example:
struct st_a
{
int a;
};
struct st_b
{
int b;
};
union un_c
{
struct st_a aa;
struct st_b bb;
};
struct st_d
{
int d;
union un_c cc;
};
int main ()
{
struct st_d *dd = malloc (sizeof (struct st_d));
dd->d = 0;
/* The following two lines might (probably are) accessing
the same area of memory. */
dd->cc.aa.a = 0;
dd->cc.bb.b = 1;
}

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;
};

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;}

Nested linked lists in C

I'm trying to implement a nested linked list in C, that will be used for a hierarchical menu. However, the GCC (v4.9.3-1) is complaining to nested structures, and I have no idea how to fix this. Here is the minimum (non)working example.
Is this nesting even possible in C?
main.c
#include "menu.h"
int main(void) {
Init_Menu();
return 0;
}
menu.c
#include "menu.h"
MenuItem_t LVL_0_MainMenu = {
.size = 0,
};
MenuItem_t LVL_1_Measurements = {
.size = 0,
};
void Init_Menu(void) {
Menu_Add_Child(&LVL_0_MainMenu, &LVL_1_Measurements);
}
void Menu_Add_Child(MenuItem_t *parent, MenuItem_t *child) {
parent->children[parent->size] = child;
child->parent = parent;
parent->size++;
}
menu.h
typedef struct {
unsigned char size;
MenuItem_t children[10];
MenuItem_t *parent;
} MenuItem_t;
extern MenuItem_t LVL_0_MainMenu;
extern MenuItem_t LVL_1_Measurements;
void Init_Menu(void);
void Menu_Add_Child(MenuItem_t *parent, MenuItem_t *child);
Based on answers by #bolov and #sps (once again, thanks to both of them), here is the minimum working example:
main.c
#include "menu.h"
int main(void) {
Init_Menu();
return 0;
}
menu.c
#include "menu.h"
MenuItem_t LVL_0_MainMenu = {
.size = 0,
};
MenuItem_t LVL_1_Measurements = {
.size = 0,
};
void Init_Menu(void) {
Menu_Add_Child(&LVL_0_MainMenu, &LVL_1_Measurements);
}
void Menu_Add_Child(MenuItem_t *parent, MenuItem_t *child) {
parent->children[parent->size] = child;
child->parent = parent;
parent->size++;
}
menu.h
struct MenuItem_t {
unsigned char size;
struct MenuItem_t *children[10];
struct MenuItem_t *parent;
};
typedef struct MenuItem_t MenuItem_t;
extern MenuItem_t LVL_0_MainMenu;
extern MenuItem_t LVL_1_Measurements;
void Init_Menu(void);
void Menu_Add_Child(MenuItem_t *parent, MenuItem_t *child);
The difference between this corrected program and the original (non)working program, is that the children array is defined as an array of pointers to variables of the type MenuItem_t instead of the array of variables of the same type. The other difference is that a nested list (inside the structure) should also contain the keyword struct as #bolov explained.
You need to use struct for the type used inside itself, even if you typedef it later on.
E.g. this won't work:
struct X_ {
X* next;
};
typedef struct X_ X;
But this will
struct X_ {
struct X_* next;
};
As a side note, I really don't like this form:
typedef struct {
} X;
I use:
struct X {
};
typedef struct X X;
But maybe this is just me being more fond of C++.
If you want to use that form, it's the same: you need to add struct and it works:
typedef struct {
struct X2* next;
} X2;
regarding:
struct X {
struct X arr[10];
};
You can't have that! The array is just in our way to understand why. So let's simplify:
struct X {
int a;
struct X var;
};
This can't be. What size would X be? sizeof(X) = sizeof(int) + sizeof(X) + padding. Do you see the problem? All you can do is have a pointer to X, but not an object X inside X.
Returning to your array. You need dynamic arrays:
struct X {
struct X* arr;
int arr_size;
};
It gets more complicated as you need to manage the memory (malloc/free fun), but you can't avoid it.
First of all, you cannot do,
typedef struct {
SomeName_t some_var;
} SomeName_t;
You need to do,
typedef struct somename {
struct somename some_var;
} SomeName_t;
Also, a struct cannot have a member which is an array of structure itself. However, a struct can have a member which is an array of pointer to the same structure.
struct foo {
struct foo foo_arr[10]; /* Will give error */
struct foo *foo_ptr_arr[10]; /* Legal */
};
However, I dont see a reason that your children member should be an array of struct anyways. Because, as can be seen in menu.c, you are doing
parent->children[parent->size] = child;
where the type of child is MenuItem_t *. So I think you basically wanted MenuItem_t.children to be an array of MenuItem_t *, and not an array of MenuItem_t.
So making this change should resolve your issue:
menu.h
typedef struct menuitem {
unsigned char size;
/* MenuItem_t children[10]; */ /* Not possible */
struct menuitem *children[10]; /* This is what you want to do */
struct menutem *parent;
} MenuItem_t;

error: dereferencing pointer to incomplete type

Looked through many other SO posts related to this, but none were able to help me. So, I have the following structs defined:
typedef struct
{
int created;
double data;
int timeLeft;
int destination;
}dataPacket;
typedef struct
{
dataPacket *array;
int currIndex;
int firstIndex;
int nextTick;
int maxLength;
int length;
int stime;
int total;
}packetBuffer;
typedef struct{
int mac;
struct wire *lconnection;
struct wire *rconnection;
int numRecieved;
struct packetBuffer *buffer;
int i;
int backoff;
}node;
typedef struct{
float length;
float speed;
int busy;
struct dataPacket *currPacket;
struct node *lnode;
struct node *rnode;
}wire;
And then I'm trying to use the following function:
int sendPacket(node *n, int tick)
{
if(n->buffer->length > 0)
{
if(n->backoff <= 0)
{
if (n->lconnection->busy != 0 || n->lconnection->busy != 0)
{
n->i++;
n->backoff = (512/W * genrand()*(pow(2,n->i)-1))/TICK_LENGTH;
}
else
{
n->lconnection->busy = 1;
n->rconnection->busy = 1;
n->lconnection->currPacket = n->buffer[n->buffer->currIndex];
n->rconnection->currPacket = n->buffer[n->buffer->currIndex];
}
}
else
{
n->backoff--;
}
}
}
I'm getting the error described in the title everytime I try to access a member of buffer, lconnection, or rconnection.
struct packetBuffer *buffer;
You've defined a type packetBuffer (a typedef for an otherwise anonymous struct).
You haven't defined struct packetBuffer.
In the absence of an existing type struct packetBuffer, the compiler treats it as an incomplete type, assuming that you'll complete it later. The declaration
struct packetBuffer *buffer;
is perfectly legal, but you can't dereference buffer unless the type struct packetBuffer is visible.
Just drop the struct keyword.
(My personal preference is to drop the typedef and consistently refer to struct types as struct whatever, but that's a matter of style and taste.)
The following:
typedef struct {
int x;
char *y;
...
} my_struct;
creates an identifier for an anonymous structure. In order, for a structure to refer to an instance of itself, it must not be "anonymous":
typedef struct my_struct {
int x;
char *y;
struct my_struct *link
....
} my_struct_t;
This means that my_struct_t is now the type struct my_struct and not just an anonymous struct. Also, note that struct my_struct can be used within its own structure definition. That is not possible with anonymous structs.
As a final complication, the my_struct in struct my_struct is in a differenct "namespace" than the my_struct_t. This is sometimes used to to simplify (or confuse) things in code like this:
typedef struct my_struct {
int x;
char *y;
struct my_struct *link
....
} my_struct;
Now I can use my_struct anywhere in my code instead of struct my_struct.
Finally, you could separate the typedef from the structure definition to achieve the same effect:
struct my_struct {
int x;
char *y;
struct my_struct *link;
....
};
typedef struct my_struct my_struct;
As noted in David R.Hanson's C Interfaces and Implementations, "This definition is legal because structure, union, and enumeration tags occupy a same name space that is separate from the space for variables, functions, and type names."

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