How to assign series of integers to pointer var in struct - c

Using c language, If I have I declared four random integers how do I go about storing them inside the series variable and then accessing them?
int a =3;
int b=4;
int c=5;
int d=6;
typedef struct struct1
{
int *series;
int num1;
double num2;
double num3;
}
Struct1;
I declared the struct as
Struct1 mystruct;

First of all you allocate the memory you need to store them using malloc. You'll need to include <stdlib.h> to access that function. You need enough space for 4 int so:
mystruct.series = malloc(4 * sizeof(int));
Then you just store and access the data like you'd do for any other array:
mystruct.series[0] = a;
mystruct.series[1] = b;
mystruct.series[2] = c;
mystruct.series[3] = d;
Once you don't need it anymore, remember to free the memory to avoid a memory leak with free(mystruct.series).

Related

Realloc struct with ** pointer to another struct

How can I realloc a double pointer inside a struct to another struct?
The double pointer is not used as a 2d array.
Code example.
struct x_tag {
int a;
int b;
};
typedef struct x_tag x_t;
struct y_tag {
x_t ** p;
int n;
};
typedef struct y_tag y_t;
/////////////////////////////////
y_t * d = malloc(sizeof(*d));
x_t * c = malloc(sizeof(*c));
d->p = &c;
/////////////////////////////
d->p = realloc(d->p, d->n*sizeof(x_t)); doesn't work.
d->p[0] = realloc(d->p[0], d->n*sizeof(x_t)); doesn't work.
*(d->p) = realloc(*(d->p), d->n*sizeof(x_t)); doesn't work.
*(d->p)[0] = realloc(*(d->p)[0], d->n*sizeof(x_t)); doesn't work.
Any ideas?
///////More info////////
The struct was not defined by me, but unfortunately I need to use this. Double pointers does not make sense to me either in this case.
The main idea is to change the size of (y_t **p) dinamically. The program should change the double pointer size every time another struct (x_t) is added.
|*d|--->|struct y_t|--->|**p|--->|*p|--->|struct x_t [0]|
|----->n |----->|struct x_t [1]|
|----->|struct x_t [2]|
I change the code to:
y_t * d = malloc(sizeof(*d));
d->p = malloc(sizeof(*d->p));
d->p[0] = malloc(sizeof(*d->p[0]));
Not working.

Malloc array of struct in C

Here is what I do:
I count the number of file inside a folder, get data from this file inside a array of struct.
I want to malloc this array of struct, since I do not know the exact number of file before strating the program.
Here is my code:
struct get_data{
int sequence;
int mask_ID;
char *name;
float intensity;
float angle_correction;
double points[10000];
float X_interval;
};
struct get_data all_data[number_of_file];
Consider I get number_of_file before somewhere in the program.
I want to know how to malloc the struct all_data. I search but got lost at some point. Any help would be welcomed. Thank you.
Mel.
I suggest you give a fixed length to the name variable inside the structure or else you would have to malloc that for each structure. The declaration could look like this:
struct get_data
{
int sequence;
int mask_ID;
char name[256];
float intensity;
float angle_correction;
double points[10000];
float X_interval;
};
Then, you may malloc an array of structures using the following code:
struct get_data *all_data;
all_data = malloc(number_of_files * sizeof(struct get_data));
if (all_data == NULL)
{
printf("Malloc failed!\n);
return -1;
}
/* now you can access each file structure using a for instruction */
int i;
for (i = 0; i < number_of_files; i++)
{
all_data[i].sequence = ...;
/* etc. */
}

Varying the Size of a Structure?

I have created a structure called Register, with around 8 fields within it. I now want to create a structure called Instrument, which should have a variable amount of of fields, 6 which are the same for every instrument, plus a certain amount of fields depending on how many registers are attributed to it. How can I create this?
For clarity here is what I would like to create (although may not be accurate).
typedef struct {
int x;
int y;
int z;
} Register;
typedef struct {
int x;
int y;
int z;
Register Reg1;
Register Reg2;
...
} Instrument;
You can make use of flexible array members to achieve the same.
Something like
typedef struct {
int x;
int y;
int z;
Register Reg1;
Register Reg2; //upto this is fixed....
Register Reg[];
} Instrument;
and then, you can allocate memory as needed to someVar.Reg later.
For an example, quoting C11, chapter ยง6.7.2.1/20
EXAMPLE 2 After the declaration:
struct s { int n; double d[]; };
the structure struct s has a flexible array member d. A typical way to use this is:
int m = /* some value */;
struct s *p = malloc(sizeof (struct s) + sizeof (double [m]));
and assuming that the call to malloc succeeds, the object pointed to by p behaves, for most purposes, as if
p had been declared as:
struct { int n; double d[m]; } *p;
You can use pointers
typedef struct
{
int x;
int y;
int z;
Register *reg;
} Instrument;
use it into code
Instrument a.reg = malloc(sizeof(Register)*NUM_OF_REGISTERS);
if (a.reg != NULL)
{
// your STUFF
free(a.Reg);
}

Discussion around functionpointers in array of structs. What are good practises?

is there a more compact way for using function pointers inside a struct ?
Do I really need to type defining the function pointer? I tried without but received type errors. Are there any hazards, or anything that I've done that is against good code practice?
#include <stdio.h>
#include <math.h>
void lineFunc(int* a)
{
int x1 = a[0];
int y1 = a[1];
int x2 = a[2];
int y2 = a[3];
double length = sqrtf( pow( (x1-x2),2 )+ pow((y1-y2),2) );
printf("%f\n", length);
}
void areaFunc(int* a)
{
int base = a[0];
int height = a[1];
int area = base*height;
printf("%d",area);
}
typedef void (*Operation)(int* a );
typedef struct CALC_TYPE
{
Operation opt
} CALC;
int main()
{
int lineArg[4] = {1 , 2, 3, 4}; //x1, y1, x2, y2
int areaArg[2] = {5,10}; // base, height
void (*lineCalc)(int*);
void (*areaCalc)(int*);
lineCalc = lineFunc;
areaCalc = areaFunc;
CALC line;
CALC area;
CALC* cmdArray = calloc(2,sizeof(CALC));
line.opt = lineFunc;
area.opt = areaFunc;
cmdArray[0]=line;
cmdArray[1]=area;
cmdArray[0].opt(lineArg);
cmdArray[1].opt(areaArg);
return 0;
}
is there a more compact way for using function pointers inside a struct ?
No.
Do I really need to type defining the function pointer?
No, but it makes your code much more readable because the notation for function pointers is arcane. You could have instead written.
typedef struct CALC_TYPE
{
void (*opt) (int*);
} CALC;
Are there any hazards, or anything that I've done that is against good code practice?
Not really. Making a struct that only contains 1 thing is questionable, but it's obviously a learning exercise.
The typedef Operation and some variables are useless. The struct too but If I've understood you, you want to keep it. So here is a more compacte way:
#include <stdio.h>
#include <math.h>
#include <stdlib.h> // calloc
void lineFunc(int* a)
{
// ...
}
void areaFunc(int* a)
{
// ...
}
typedef struct CALC_TYPE
{
void (*opt)(int *a);
} CALC;
int main()
{
int lineArg[4] = {1 , 2, 3, 4}; //x1, y1, x2, y2
int areaArg[2] = {5,10}; // base, height
CALC *cmdArray = calloc(2, sizeof(CALC));
cmdArray[0].opt = lineFunc;
cmdArray[1].opt = areaFunc;
cmdArray[0].opt(lineArg);
cmdArray[1].opt(areaArg);
free(cmdArray); // 1 malloc/calloc => 1 free
return 0;
}
EDIT:
Are there any hazards, or anything that I've done that is against good
code practice?
Include stdlib.h to use calloc
Don't forget to free dynamically allocated memory
Why pow then sqrtf then store in double ? Use sqrt instead
You could avoid the use of a struct here
One additional point that I did not see in the other answers concerns a benefit of struct usage: function prototype stability. Even if a struct starts out with a single variable, future requirements for the struct may force more variables to be added. Because of the way struct variables are passed as arguments, prototype's of functions written to use the original single single variable struct, will not be broken when additional variables are added.
For example, your struct can be defined as:
typedef struct CALC_TYPE
{
Operation opt
} CALC;
Or:
typedef struct CALC_TYPE
{
Operation opt
int a;
float b;
} CALC;
Without forcing change to a function that calls it.:
void func(CALC *c)
{
...
}
It's a great way to allow changes to the number of items that need to be passed as data without changing the argument list.
Using a modification of your area function, consider the following struct that was initially designed to support area measurements:
typedef struct
{
int length;
int width;
}DIM;
int areaFunc(DIM *d)
{
return d->length*d->width*d
}
Later a requirement for the struct to support volume forces the addition of a variable:
typedef struct
{
int length;
int width;
int height;
}DIM;
Adding the new variable to the struct does not break the existing areaFunc(), but also supports the new function:
int volumeFunc(DIM *d)
{
return d->length*d->width*d->height;
}

Run-Time Conditional Fields in Structs in C

I have a specific application written in C that needs to be memory efficient. It is collecting statistics, so I need to be able to "turn on/off" certain fields in run-time to minimize the memory consumption.
I know you can define conditional struct fields using macros but that is compile-time if I'm not mistaken, is there a possible way of doing this in C in run-time?
Example:
input :
collect (A,B)
will result in a struct like this:
struct statistics{
double A;
double B;
};
but input:
collect (A,B,C)
will result in a struct like this:
struct statistics{
double A;
double B;
double C;
};
Its not possible to turn-off certain fields inside the struct at run-time. You can however have a pointer that points to a dynamically allocated array of doubles that can represent multiple fields.
For example:
#include <stdio.h>
#include <stdlib.h>
struct stats
{
size_t number_of_doubles;
double* data;
};
void make_stats(struct stats* pStats)
{
pStats->number_of_doubles = 3;
pStats->data = (double*) malloc(pStats->number_of_doubles * sizeof(double));
}
void delete_stats(struct stats* pStats)
{
free(pStats->data);
}
int main()
{
struct stats foo;
make_stats(&foo);
foo.data[0] = 3.0;
foo.data[1] = 5.0;
foo.data[2] = 7.0;
delete_stats(&foo);
return 0;
}
Instead of the usual array of structs (AoS):
struct statistics{
double A;
double B;
double C;
};
struct statistics my_statistics = malloc(1000000 * sizeof(my_statistics[0]));
my_statistics[0].A = 1;
my_statistics[0].B = 2;
my_statistics[0].C = 3;
you could switch to a struct of arrays (SoA):
struct statistics{
double *A;
double *B;
double *C;
};
struct statistics my_statistics;
my_statistics.A = using_A ? malloc(1000000 * sizeof(my_statistics.A[0])) : NULL;
my_statistics.B = using_B ? malloc(1000000 * sizeof(my_statistics.B[0])) : NULL;
my_statistics.C = using_C ? malloc(1000000 * sizeof(my_statistics.C[0])) : NULL;
my_statistics.A[0] = 1;
my_statistics.B[0] = 2;
my_statistics.C[0] = 3;
There is no way to alter the size of a struct at runtime. The size of a struct is built into the executable's instructions whenever you allocate them on the stack or on the heap. As another example, sizeof of a struct is available at compile time, so it can not be altered at runtime.
Of course, you can have custom structs with a custom memory manager to do that, but it's not built right into the language.

Resources