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;
}
Related
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.
While for simple types (simple types: int, char..) we directly use pointers (their address) as an argument to a function to permanently change their value in the main program, can someone explain to me why for structures we need a pointer to a Structure pointer, and not just a pointer?
struct someStruct
{
int field1;
int field2;
}
void initializeFields(struct someStruct** foo)
{
//changing fields
}
//while
void initializeFields(struct someStruct* foo) //does not work ?
struct someStruct* foo is fine, you don't need struct someStruct** foo. Not sure where you got that idea from, but it's not correct.
To only change the members of the structure you don't need that. But to change the actual pointer to the structure you need to emulate pass by reference by using pointer to a pointer to the structure.
For example, to only change a member this is enough
void initializeFields(struct someStruct* foo)
{
foo->field1 = 1;
foo->field2 = 2;
}
int main(void)
{
struct someStruct bar;
initializeFields(&bar);
printf("field1 = %d\n", bar.field1);
printf("field2 = %d\n", bar.field2);
return 0;
}
But if you for example want to dynamically allocate the structure in the function you need to emulate pass by reference:
void initializeFields(struct someStruct** foo)
{
// The difference is this assignment
*foo = malloc(sizeof(struct someStruct));
(*foo)->field1 = 1;
(*foo)->field2 = 2;
}
int main(void)
{
struct someStruct* bar;
initializeFields(&bar);
printf("field1 = %d\n", bar->field1);
printf("field2 = %d\n", bar->field2);
return 0;
}
Two more examples to show the difference between pass by value and emulating pass by reference.
Consider the following program:
#include <stdio.h>
void foo(int y)
{
y = 5;
}
int main(void)
{
int x = 1;
printf("1: x = %d\n", x);
foo(x);
printf("2: x = %d\n", x);
return 0;
}
The above program will print
1: x = 1
2: x = 1
That is because a copy of the value in x is passed to the function foo. Modifying the local copy inside foo will not modify the original variable x inside main.
Now to emulate pass by reference:
#include <stdio.h>
void foo(int *y)
{
*y = 5;
}
int main(void)
{
int x = 1;
printf("1: x = %d\n", x);
foo(&x);
printf("2: x = %d\n", x);
return 0;
}
This program will print
1: x = 1
2: x = 5
This is because we don't change the pointer variable y inside the function foo, but we change the value of where it points, which happens to be the variable x in the main function.
There are very specific cases where you need pointer to a struct pointer (array of struct pointers, mostly).
Otherwise, a pointer to a struct is enough.
struct someStruct
{
int field1;
int field2;
}
void initializeFields(struct someStruct* foo)
{
foo->field1 = 42;
foo->field2 = -1;
}
Take in mind the following piece of code:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int a;
int b;
int c;
}A;
A *test;
void init(A* a)
{
a->a = 3;
a->b = 2;
a->c = 1;
}
int main()
{
test = malloc(sizeof(A));
init(test);
printf("%d\n", test->a);
return 0;
}
It runs fine! Now imagine that I want to use the malloc function outside the main itself without returning a pointer to the struct. I would put malloc inside init and pass test adress. But this doesnt seem to work.
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int a;
int b;
int c;
}A;
A *test;
void init(A** a)
{
*a = malloc(sizeof(A));
*a->a = 3;
*a->b = 2;
*a->c = 1;
}
int main()
{
init(&test);
printf("%d\n", test->a);
return 0;
}
It keeps telling me that int a(or b/c) is not a member of the struct A when I use the pointer.
Your problem is operator precedence. The -> operator has higher precedence than the * (dereference) operator, so *a->a is read as if it is *(a->a). Change *a->a to (*a)->a:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int a;
int b;
int c;
}A;
A *test;
void init(A** a)
{
*a = malloc(sizeof(A));
(*a)->a = 3;
(*a)->b = 2;
(*a)->c = 1;
}
int main()
{
init(&test);
printf("%d\n", test->a);
return 0;
}
You must add parenthesis:
void init(A **a)
{
*a = malloc(sizeof(A)); // bad you don't verify the return of malloc
(*a)->a = 3;
(*a)->b = 2;
(*a)->c = 1;
}
But it's good practice to do this:
void init(A **a)
{
A *ret = malloc(sizeof *ret); // we want the size that is referenced by ret
if (ret != NULL) { // you should check the return of malloc
ret->a = 3;
ret->b = 2;
ret->c = 1;
}
*a = ret;
}
You need to write (*a)->a = 3; for reasons of precedence.
Even though it's not a direct answer to your question, since we're in the vicinity of initialization I'd like to point out that C11 gives you a nicer syntax to initialize structs:
void init(A **a)
{
A *ret = malloc(sizeof *ret); // we want the size that is referenced by ret
if (ret != NULL) { // you should check the return of malloc
*ret = (A) {3, 2, 1};
// or
*ret = (A) { .a = 3, .b = 2, .c = 1 };
}
*a = ret;
}
Another advantage is that any uninitialized members are zeroed.
After some research I didn't find a good way to implement the std::bind in C.
I build a small program that implements an equivalent of std::bind in C by hacking the stack.
There's two functions I will try to bind to function with pre-defined arguments.
My problem is this code is only working under Windows. Under Linux, this is a mess. I this the problem is my knowledge of the stack and the way that arguments are store in memory.
Thanks,
Please, find below the code I made:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
The two functions I want to bind :
void test1 (int nombre, char t, int nombre2)
{
printf ("test 1 : %d%c%d\n", nombre, t, nombre2);
}
void test2 (char t, int nombre, int nombre2)
{
printf ("test 2 : %c%d%d\n", t, nombre, nombre2);
}
Two struct that will store the argument of each function (order of fields is important).
typedef struct {
int nombre;
char t;
int nombre2;
} struct1;
typedef struct {
char t;
int nombre;
int nombre2;
} struct2;
This "fake" struct will be use to write on the stack by dereferencing a structvoid* variable.
// Size must be bigger than every struct*
typedef struct {
int i[10];
} structvoid;
The main function.
int main(int argc, char** argv) {
// Variables to store the two functions and their arguments.
void * functions[2];
structvoid * data[2];
void *func1 = (void *)&test1;
void *func2 = (void *)&test2;
void (*functionPtrc)(structurevoid);
// Definition of the argument of the first function test1
struct1 data1;
data1.nombre = 15;
data1.t = 'c';
data1.nombre2 = 30;
// and storing data.
void *datac = malloc (sizeof (structvoid));
memcpy(datac, &data1, sizeof (struct1));
data[0] = (structvoid*)datac;
functions[0] = func1;
// Same thing with function 2.
struct2 data2;
data2.t = 'a';
data2.nombre = 5;
data2.nombre2 = 10;
datac = malloc (sizeof (structvoid));
memcpy(datac, &data2, sizeof (struct2));
data[1] = (structvoid*)datac;
functions[1] = func2;
// Get the pointer to the first function (test1);
functionPtrc = functions[0];
// All the hack is here. By dereferencing the data, this will write on the stack all arguments need by the test1 function.
functionPtrc(*data[0]);
functionPtrc = functions[1];
functionPtrc(*data[1]);
// To check the result.
test1 (data1.nombre, data1.t, data1.nombre2);
test2 (data2.t, data2.nombre, data2.nombre2);
return 0;
}
EDIT
Here a new version of the program by calling function via the calling convention. I only wrote the new lines. The problem of this method is I can only store data inside a "void *" field. If I increase the size of structvoid, I got garbage behaviors.
// Structure that memories each argument
typedef struct {
void *i[1];
} structvoid;
int main(int argc, char** argv) {
// Variables to store the two functions and their arguments.
void * functions[2];
structvoid * data[2];
void *func1 = (void *)&test1;
// Let's start with a maximum of 5 arguments
void (*functionPtrc)(structurevoid, structurevoid, structurevoid, structurevoid, structurevoid);
// Definition of the argument of the first function test1
struct1 data1;
data1.nombre = 15;
data1.t = 'c';
data1.nombre2 = 30;
// and storing data.
structvoid *datac = malloc (sizeof (structvoid)*5);
memcpy(&datac[0], &data1.nombre, sizeof (data1.nombre));
memcpy(&datac[1], &data1.t, sizeof (data1.t));
memcpy(&datac[2], &data1.nombre2, sizeof (data1.nombre2));
data[0] = datac;
functions[0] = func1;
// Get the pointer to the first function (test1);
functionPtrc = functions[0];
// Call the function with the arguments. The unused argument will be ignored.
functionPtrc(data[0][0], data[0][1], data[0][2], data[0][3], data[0][4]);
}
If I have a struct in C that has an integer and an array, how do I initialize the integer to 0 and the first element of the array to 0, if the struct is a member another struct so that for every instance of the other struct the integer and the array has those initialized values?
Initialisers can be nested for nested structs, e.g.
typedef struct {
int j;
} Foo;
typedef struct {
int i;
Foo f;
} Bar;
Bar b = { 0, { 0 } };
I hope this sample program helps....
#include <stdio.h>
typedef struct
{
int a;
int b[10];
}xx;
typedef struct
{
xx x1;
char b;
}yy;
int main()
{
yy zz = {{0, {1,2,3}}, 'A'};
printf("\n %d %d %d %c\n", zz.x1.a, zz.x1.b[0], zz.x1.b[1], zz.b);
return 0;
}
yy zz = {{0, {0}}, 'A'}; will initialize all the elements of array b[10] will be set to 0.
Like #unwind suggestion, In C all instances created should initialized manually. No constructor kind of mechanism here.
You can 0-initialize the whole struct with {0}.
For example:
typedef struct {
char myStr[5];
} Foo;
typedef struct {
Foo f;
} Bar;
Bar b = {0}; // this line initializes all members of b to 0, including all characters in myStr.
C doesn't have constructors, so unless you are using an initializer expression in every case, i.e. write something like
my_big_struct = { { 0, 0 } };
to initialize the inner structure, you're going to have to add a function and make sure it's called in all cases where the structure is "instantiated":
my_big_struct a;
init_inner_struct(&a.inner_struct);
Here is an alternative example how you would do things like this with object-oriented design. Please note that this example uses runtime initialization.
mystruct.h
#ifndef MYSTRUCT_H
#define MYSTRUCT_H
typedef struct mystruct_t mystruct_t; // "opaque" type
const mystruct_t* mystruct_construct (void);
void mystruct_print (const mystruct_t* my);
void mystruct_destruct (const mystruct_t* my);
#endif
mystruct.c
#include "mystruct.h"
#include <stdlib.h>
#include <stdio.h>
struct mystruct_t // implementation of opaque type
{
int x; // private variable
int y; // private variable
};
const mystruct_t* mystruct_construct (void)
{
mystruct_t* my = malloc(sizeof(mystruct_t));
if(my == NULL)
{
; // error handling needs to be implemented
}
my->x = 1;
my->y = 2;
return my;
}
void mystruct_print (const mystruct_t* my)
{
printf("%d %d\n", my->x, my->y);
}
void mystruct_destruct (const mystruct_t* my)
{
free( (void*)my );
}
main.c
int main (void)
{
const mystruct_t* x = mystruct_construct();
mystruct_print(x);
mystruct_destruct(x);
return 0;
}
You don't necessarily need to use malloc, you can use a private, statically allocated memory pool as well.