gl*******@hotma il.com writes:
Let's assume that I have the following structure and the following
array:
struc My_struct
{
char var_one;
char var_two;
char var_three;
};
struct My_struct testing;
char My_array[3]={43, 13, 32};
Is there a fast way of initializing the variables of "testing" with the
values of the My_array?
I would like the following
testing.var_one = 43;
testing.var_two = 13;
testing.var_thr ee = 32;
Basically I am missing a function like fread which reads data from a
file. Instead I would like to read it from an array. Having only three
variables may not be an issue, but if the structure has 100 variables
it is a tedious work to assign the values of each array-cell to each
variable in the structure...
And in a followup, the original poster writes: I found the answer. memcpy solves the problem.
memcpy(testing, my_array, 3);
The problem with this is that there's no guarantee that the elements
of the structure are allocated contiguously. The compiler is free to
insert padding between members and/or after the last member. Usually
it will do so only as necessary to meet alignment requirements, but it
can legally insert padding based on the phase of the moon.
The only guaranteed portable way to do what you're trying to do is to
assign each member:
testing.var_one = my_array[0];
testing.var_two = my_array[1];
testing.var_thr ee = my_array[2];
The best approach is probably to decide in the first place whether you
want to use an array or a structure, and use one or the other
consistently.
--
Keith Thompson (The_Other_Keit h)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.