I want some 2d array
const int a = 5;
const int b = 10;
double R[a][b];
then I want to assign 5 numbers: {0.2, 0.3, 0.4, 0.5, 0.6} to [a] index of the R 2d array. Is it possible?
CodePudding user response:
For variable-sized arrays, where the lengths are computed at runtime, you cannot use an initializer. If there is a pattern in the initial values you typically use a for loop. On the other hand, if the lengths can be computed at compile-time you can instead use an array initializer. Here are examples of both cases:
#include <stdio.h>
#define LEN(array) ((int) (sizeof (array) / sizeof (array)[0]))
int main(void)
{
const int a = 10, b = 5;
double R[a][b];
for (int i = 0; i < LEN(R); i ) {
R[i][0] = 0.2;
R[i][1] = 0.3;
R[i][2] = 0.4;
R[i][3] = 0.5;
R[i][4] = 0.6;
}
double R1[][10] ={
{0.2, 0.3, 0.4, 0.5, 0.6},
{0.2, 0.3, 0.4, 0.5, 0.6},
{0.2, 0.3, 0.4, 0.5, 0.6},
{0.2, 0.3, 0.4, 0.5, 0.6},
{0.2, 0.3, 0.4, 0.5, 0.6},
{0.2, 0.3, 0.4, 0.5, 0.6},
{0.2, 0.3, 0.4, 0.5, 0.6},
{0.2, 0.3, 0.4, 0.5, 0.6},
{0.2, 0.3, 0.4, 0.5, 0.6}};
return 0;
}
Note: By computing the length of R with the sizeof operator, instead of using length variables (a and b) used in its declaration, the logic becomes less fragile. To get the number of columns in the example you use LEN(R[0])
.