我试图找到一种方法,将一个特定的列分配给多维数组中的特定值
根据下面的内容,我知道如何通过for循环手动分配它。
有没有更简单的方法去做呢?谢谢
#include < stdio.h >
double Test1[4][5];
double a0, a1, a2, a3;
int main() {
//Assigning one column in a specific row manually
Test1[1][1] = 1;
a0 = Test1[0][1];
a1 = Test1[1][1];
a2 = Test1[2][1];
a3 = Test1[3][1];
printf("a0 %f \r\n", a0);
printf("a1 %f \r\n", a1);
printf("a2 %f \r\n", a2);
printf("a3 %f \r\n", a3);
int row = sizeof(Test1) / sizeof(Test1[0]);
printf("rows %d \r\n", row);
int column = sizeof(Test1[0]) / sizeof(Test1[0][0]);
printf("cols %d \r\n", column);
int L;
double a;
//Assigning one column in all rows to one
for (L = 0; L < row; L = L + 1) {
Test1[L][1] = 1;
}
a0 = Test1[0][1];
a1 = Test1[1][1];
a2 = Test1[2][1];
a3 = Test1[3][1];
printf("a0 %f \r\n", a0);
printf("a1 %f \r\n", a1);
printf("a2 %f \r\n", a2);
printf("a3 %f \r\n", a3);
return 0;
}
最佳答案
没有设置二维数组列的标准函数。在C语言中,多维数组有点像幻觉;它们编译成一维数组。下面是一些代码,演示如何将值展开为1D数组:
#include <stdio.h>
int main(){
int test[10][2] = {0};
//point to the 1st element
int * p1 = &test[0][0];
//20th position is the 9th row, 2nd column
p1[19] = 5;
//9th element is the 5th row, 1st column
int * p2 = p1 + 8;
*p2 = 4;
printf("Value set to 5: %d\n",test[9][1]);
printf("Value set to 4: %d\n",test[4][0]);
}
关于c - 为多维数组(C)中的特定列分配值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44439113/