Reputation: 26315
I have these variables:
val1 = 24.00
val2 = 71.3
val3 = 9.30
val4 = 45.3
and I want to insert them in an array.
array[0] = 24.00
array[1] = 71.3
array[2] = 9.30
array[3] = 45.3
Is there any way to do this. Sorry I am trying to get my head around arrays in C and this is all I have so far:
double array[5];
for (i=0; i<5; i++) {
array[i] = val1
array[i] = val2
array[i] = val3
array[i] = val4
}
I know this is not right but I am unsure of how to insert variable elements into an array. Any help would be appreciated.
Upvotes: 1
Views: 83
Reputation: 2624
Your sample code will end up with val4 in each element because the code in the brackets runs once per iteration and val4 is the final statement each iteration. The variables being in discrete variables makes it rather difficult to do what you are asking inside of a loop. I am afraid the best you can do is assign them manually as you demonstrated. You could possibly achieve this with a preprocessor macro but that would be compiler dependent and quite ugly.
Upvotes: 2
Reputation: 13806
Either use a loop, or assign each element, but do not mix them. If the values are in several variables:
double array[4];
array[0] = val1
array[1] = val2
array[2] = val3
array[3] = val4
If you have them in another array:
double array[4];
double val[] = {24.00, 71.3, 9.30, 45.3};
for (i=0; i<4; i++) {
array[i] = val[i]
}
Upvotes: 2
Reputation: 30813
You have already done it half way except that you got to change your value with the variable names:
array[0] = val1;
array[1] = val2;
array[2] = val3;
array[3] = val4;
If you have val
variable as array, then you could use memcpy or for loop to do it.
Example:
double val[] = {24.00, 71.3, 9.30, 45.3};
double array[4];
memcpy(array, val, 4 * sizeof(double));
Also, this is not the way to do that because you overwrite what you previously write:
double array[5];
for (i=0; i<5; i++) {
array[i] = val1;
array[i] = val2;
array[i] = val3;
array[i] = val4;
}
All elements of array will be val4
Upvotes: 2