简体   繁体   中英

inserting elements in array

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.

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

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]
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM