Home > OS >  three variables=1array 1 heap allocated memory& uint64 type variable changing 1 array should reflect
three variables=1array 1 heap allocated memory& uint64 type variable changing 1 array should reflect

Time:03-04

So this is my minimal produced code

float *validate_c=malloc(sizeof(float)*2);
uint64_t c;
float cl[2];

But I could not try to figure out any solution that changing in validate_c should automatically be reflected in cl. I know cl has cl 0 and cl 1 address so I was thinking assigning at these two memory address to the other this can work but I dont want this i can assign validate_c to cl only through uint64_t c

something like dividing c to contain address for all validate_c so there should be 1 to 1 index matching is it possible in C, but it sounds wrong, I really dont want this this way. can I do this and what if my validate_c and cl would be huge then what would be the solution

CodePudding user response:

You want a pointer to float and an array of float so that accessing to consecutive floats via the pointer also affects the values in the array.
If you use malloc() for initialising the pointer, you will end up with two separate memory areas, one malloced one in the defined array.
In order to have the desired effect just point the pointer to the defined array.

float cl[2];
float *validate_c=cl;

This achieves this part of your description

changing in validate_c should automatically be reflected in cl.

I think this is what you want.

The part about

dividing c to contain address for all validate_c

I think you are only trying to achive the above. So I consider the proposed solution above to be the answer to your question.

If you want to access the same values via validate_cl, cl AND c.
We could be looking at unions. But that is risky and not 100% within standard. I won't go into details if it is not needed.

  •  Tags:  
  • c
  • Related