How do I assign a value from struct to another. Here is my code.
I believe I am assigning the address of the struct which is what I don’t want to do. I want to assign the values of “temp” to ‘a’. I commented the section I need help on. Thanks
Also off-topic.. How do I post code without having to indent myself every line, line-by-line?
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
typedef struct dynArrStruct
{
double value1;
int value2;
int value3;
}dynArr;
void init(dynArr* a)
{
dynArr temp;
temp.value1 = (double)(rand()) * rand() / rand();
temp.value2 = rand()%100;
temp.value3 = rand()%1000;
printf("In init(): value1: %14.5f, value2: %6d, value3: %6d\n",
temp.value1, temp.value2, temp.value3);
a = &temp; // THIS LINE
}
int main(int argc, char** argv)
{
int i;
dynArr a1[SIZE];
dynArr* a2[SIZE];
for(i = 0; i < SIZE; i++)
{
init(&(a1[i]));
init(a2[i]);
}
return 0;
}
Use assignment (assuming
ais pointing to valid memory):Note this works because the members of the
structare not pointers. Using this technique (ormemcpy()) on astructthat contained member pointers would result in bothstructs having members pointing to the same address, which may be dangerous (possibly resulting in dangling pointers). If astructcontains pointers then a deep copy of thestructis required (allocating memory for the member pointers and copying the pointed to objects in the source struct to the allocated memory in the destinationstruct).Also, in this case
tempis superfluous and you just assign values directly to the members ofa.