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.
Related
Below is the code, I'm so puzzled of how to use that double pointer int struct _AReport and struct _BReport.
My system is running on a Embedded computer, I use VS to debug this parts.
My system is composed of 1 struct _AReport, 17 struct _BReport and 16 struct _CReport on the whole.
The goal is that struct _AReport will contain all the informations.
I'm poor at English, thanks for being patient.
#include "stdafx.h"
typedef struct _AReport AReport;
typedef struct _BReport BReport;
typedef struct _CReport CReport;
typedef struct _AData AData;
typedef struct _BData BData;
typedef struct _CData CData;
typedef struct _ABCDatas ABCDatas;
struct _AReport
{
AData *adata;
BReport **breport;
};
struct _BReport
{
int _b;
BData *bdata;
CReport **creport;
};
struct _CReport
{
int _c;
CData *cdata;
};
int main()
{
int i = 0;
AReport Ar;
//BReport Br_dyadic[17][16] = { 0 };
BReport Br[17];
BReport *Br_Pointer = Br;
Ar.breport = &(Br_Pointer);
for (i = 0; i < 17; i++)
{
Br[i]._b = i + 1;
}
(Ar.breport[0])->_b = 99;
(Ar.breport[0] + 1)->_b = 99;
return 0;
}
If your question is does this problem require pointers to pointers, the answer is no: pointer arithmetics allow a single pointer to access all elements of a 1D array.
But if your question is does the last lines correctly access the elements of Br, then the answer it yes. Here is what actually happens:
Ar.breport is a pointer to a pointer to the first element of array Br (from BReport *Br_Pointer = Br; Ar.breport = &(Br_Pointer);, BrPointer being a pointer to first element of Br)
Ar.breport[0] is by definition the same as *(Ar.breport) => it is a pointer to the first element of Br
so Ar.breport[0] + 1 is by pointer arithmetics a pointer to the second element of Br
It is then legal to use those 2 pointers to dereference them and access the _b member of the BReport they point to.
You could make sure of that by simply adding:
printf("%d - %d - %d\n", Br[0]._b, Br[1]._b, Br[2]._b);
just before the return 0; (of after adding #include <stdio.h>...) and that should print 99 - 99 - 2
Is what am I trying to do in C possible?
#include <stdio.h>
#include <stdlib.h>
struct foo{
int const * const a; // constPtrToConst is a constant (pointer)
// as is *constPtrToConst (value)
};
struct faa{
int b;
};
int main(void){
struct foo *x = (struct foo*)malloc(sizeof(struct foo));
struct faa *y = (struct faa*)malloc(sizeof(struct faa));
x->a = &(y->b); // error: assignment of read-only member ‘a’ [that's ok]
// (I)
x->a++; // It should not do this either...
printf("%d,\t%p\n", *(x->a), x->a); // (II)
free(x);
free(y);
}
How can I initialize (I) and could I get this (II)?
Sorry is not assign is initialize with that pointer.
This is what I want to get but dynamically.
#include <stdio.h>
struct foo{
int const * const a;
};
int main(void){
int b = 5;
struct foo x = {
.a = &b
};
printf("%d\n", *(x.a));
}
This is how I solve it.
I don't know if is the best choice.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct foo{
int const * const a;
};
struct foo* newfoo(int *var){
struct foo *tempD = malloc(sizeof(struct foo));
struct foo tempS ={
.a = var
};
memcpy(tempD, &tempS, sizeof(struct foo));
return tempD;
}
int main(void){
int b = 5;
struct foo *z = newfoo(&b);
printf("%d,\t%p\n", *(z->a), z->a);
// this is equivalent to printf("%d,\t%p\n", b, &b);
free(z);
}
int const * const a; is a type of variable which is constant means that it cannot be changed (second const), while first const means that it points to constant data.
Change your structure to:
struct foo{
const int* a;
};
Now you can assign value to a but you cannot modify value where a points.
struct foo myFoo;
myFoo.a = (int *)5; //a points to location 5 now, valid
*myFoo.a = 4; //Try to modify where a points = invalid and error
What is the difference between const int*, const int * const, and int const *?
You have to use memcpy in this case; you can't assign through a const expression:
int *temp = &y->b;
memcpy((void *)&x->a, &temp, sizeof temp);
In order to effect x->a++ you could do:
int *temp;
memcpy(&temp, &x->a, sizeof temp);
++temp;
memcpy((void *)&x->a, &temp, sizeof temp);
You can't assign to x->a after initialization, so you would have to do something silly like:
struct faa *y = (struct faa*)malloc(sizeof(struct faa));
struct foo tmp = {&y->b};
struct foo *x = (struct foo*)malloc(sizeof(struct foo));
memcpy(x, &tmp, sizeof *x);
This is the same scenario:
I locked the door and threw away the key since nobody including myself should ever open that door in any situation.
Immediately after doing that, I noticed that I cannot open the door!
I need to open this door! How do I do that? I threw away the key.
You have to 1) know what you are doing, and 2) don't do things that you actually don't want to do, including not making a program design specification that contradicts the actual needs of the program.
Simply change the declaration to int const* a; if you intend to change where that pointer points at.
Why not typecasting. The following code will print 6.
int main()
{
int x = 5;
const int* c{ &x};
int* p{( int*) c};
*p = 6;
std::cout << x << std::endl;
}
To explain more, I have two structures-'first' and 'second' having common variables 'jack' and 'jill'. I want to print jack via a pointer based on if-else condition.
I understand at the time of printing I have to typecast the void pointer. But whether the pointer points to struct a or b is decided on run time.
It is a basic C code. How to overcome this?
Code
#include <stdio.h>
int main(void)
{
typedef struct one
{
int jack;
float jill;
}a;
typedef struct two
{
int jack;
float jill;
char something;
int something1;
}b;
a first;
b second;
void *z;
if(1)
{
a* z;
z = &first;
printf("First one");
}
else
{
b* z;
z = &second;
printf("Second one");
}
printf("%d\n", z->jack);
return 0;
}
Error
prog.c:36:17: warning: dereferencing 'void *' pointer printf("%d\n", z->jack); prog.c:36:17: error: request for member 'jack' in something not a structure or union
You get a compiler warning since the compiler does not understand z->jack since z is a void * (note that the declarations a* z and b* z are not valid outside the scope of the if and else block).
To overcome this you can use a function printJack as shown in the following listing:
#include <stdio.h>
typedef struct one
{
int jack;
float jill;
}a;
typedef struct two
{
int jack;
float jill;
char something;
int something1;
}b;
void printJack(void *pStruct, int type)
{
switch (type)
{
case 1:
printf("jack: %d\n", ((a *)pStruct)->jack);
break;
default:
printf("jack: %d\n", ((b *)pStruct)->jack);
break;
}
}
/*
** main
*/
int main(void)
{
a first;
b second;
void *z;
first.jack = 5;
second.jack = 4892;
printJack(&first, 1);
printJack(&second, 0);
z = &first;
printJack(z, 1);
return (0);
}
I've written code like this often and experienced a lot of trouble with it. Not at the time of implementing, since you are knowing what you are typing at that moment but let's say a few years later if you need to extend your code. You will miss a few places where you cast from void * to a * or b * and you'll spend a lot of time debugging what's going on...
Now I'm writing things like this in the following way:
#include <stdio.h>
typedef struct header
{
int jack;
float jill;
} h;
typedef struct one
{
struct header header;
/* what ever you like */
}a;
typedef struct two
{
struct header header;
char something;
int something1;
/* and even more... */
}b;
void printJack(void *pStruct)
{
printf("jack: %d\n", ((struct header *)pStruct)->jack);
}
/*
** main
*/
int main(void)
{
a first;
b second;
void *z;
first.header.jack = 5;
second.header.jack = 4892;
printJack(&first);
printJack(&second);
v = &first;
printJack(v);
return (0);
}
As you've noticed I have declared a new struct header which covers the the common parts of struct one and struct two. Instead of casting the void * to either a * or b * a "common" cast to struct header * (or h *) is done.
By doing so you can easily extend the "common attribtues" of the structs or you can implement further structs using this header and function printJack still will work. Additionally there is no need for attribute type anymore making is easier to call printJack. You can even change the type of jack without needing to change it in various places within your code.
But remember that struct header needs to be the first element of the structs you use this mechanism. Otherwise you will end up with a few surprises since you are using memory which does not contain the data of the struct header...
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.
So, I have a struct inside of other struct.. and I whant to know how I can malloc that struct...
#include <stdio.h>
#include <string.h>
struct
{
int n, o, p;
struct
{
int a, b, c;
}Str2;
}Str1;
main()
{
struct Str1.Str2 *x (Str1.Str2*)malloc(sizeof(struct Str1.Str2*));
x->a = 10;
}
So, I try that, but, not work..
How I can make this, Or is more better allocate all struct ?
You just need to allocate Str1 and Str2 would be allocated automatically. On my system, the sizeof for Str1 is 24 which equals to the size of 6 ints. Try this:
typedef struct {
int n;
int o;
int p;
struct {
int a;
int b;
int c;
}Str2;
}Str1;
main()
{
Str1 *x = (Str1 *)malloc(sizeof(Str1));
x->Str2.a = 10;
printf("sizeof(Str1) %d\n", (int)sizeof(Str1));
printf("value of a: %d\n", x->Str2.a);
}
Str1 and Str2 are objects of the anonymous structs you declared, so the syntax is way off. Did you forget some typedefs?
//declares a single object Str1 of an anonymous struct
struct
{
}Str1;
//defines a new type - struct Str1Type
typedef struct
{
}Str1Type;
To name a struct, you use
struct Str1
{
...
};
You can now use struct Str1 when you want to refer to this particular struct.
If you want to use it as Str1 only, you need to use typedef, e.g.
typedef struct tagStr1
{
...
} Str1;
Or typedef struct Str1 Str1; if we have the first type of struct Str1 declaration.
To create an instance of a struct with no name (Instance means "a variable of that type"):
struct
{
...
} Instance;
Since this struct doesn't have a name, it can't be used anywhere else, which is generally not what you want.
In C (as opposed to C++) you can not define a new type structure inside another the type definition of another structure, so
typedef struct tagStr1
{
int a, b, c;
typedef struct tagStr2
{
int x, y, z;
} Str2;
} Str1;
will not compile.
If we change the code to this:
typedef struct tagStr1
{
int a, b, c;
struct tagStr2
{
int x, y, z;
};
} Str1;
typedef struct tagStr2 Str2;
will compile - but at least gcc gives a warning for "struct tagStr2 does not declare anythign" (because it expects you wanted to actually have a member of type struct tagStr2 inside Str1.
Why not declare things like:
typedef struct
{
int a, b, c;
}Str2;
typedef struct
{
int n, o, p;
Str2 s2;
}Str1;
Then you can allocate them individually as you desire. For instance:
Str2 *str2 = (Str2*)malloc(sizeof(Str2));
Str1 *str1 = (Str1*)malloc(sizeof(Str1));
s1->s2.a = 0; // assign 0 to the a member of the inner Str2 of str1.