2d数组地址在c中,并在数组之间进行选择



我在我的c代码中有一些2d双类型数组,我想在它们之间进行选择。到目前为止,我使用的解决方案是创建另一个2d数组,并使用for{for{}}填充它。

if (some condition)
for()
for()
temp[i][j]=arr1[i][j];
else if (another condition)
for()
for()
temp[i][j]=arr2[i][j];
...

现在我尝试了以下代码

double (*temp)[4][4];
double arr1[4][4],arr2[4][4];
if (some condition)
temp = &arr1;
else if (another condition)
temp = &arr2;

最新代码的问题是它只分配了第一行,而其他行似乎得到了不正确的地址。我应该怎样纠正我的代码?

你没有告诉我们你如何使用double (*temp)[4][4];,但它是一个指针或2d数组,如果增量它将指向下一个4x4数组。您需要先参考指针(*),然后应用数组下标([][]),这需要括号('(*…)[…][…])以正确的顺序计算:

#include <stdio.h>
#define ROWS 4
#define COLS 4
int main(void) {
double (*temp)[ROWS][COLS];
double arr1[][COLS] = {
{ 1, 1, 1, 1 },
{ 1, 1, 1, 1 },
{ 1, 1, 1, 1 },
{ 1, 1, 1, 1 }
};
double arr2[][COLS] = {
{ 2, 2, 2, 2 },
{ 2, 2, 2, 2 },
{ 2, 2, 2, 2 },
{ 2, 2, 2, 2 }
};
if (1)
temp = &arr1;
else
temp = &arr2;
(*temp)[1][0] = 3;
for(size_t r = 0; r < ROWS; r++) {
for(size_t c = 0; c < COLS; c++) {
printf("%lf%s", (*temp)[r][c], c + 1 < COLS ? ", " : "n");
}
}
}

和示例:

1.000000, 1.000000, 1.000000, 1.000000
3.000000, 1.000000, 1.000000, 1.000000
1.000000, 1.000000, 1.000000, 1.000000
1.000000, 1.000000, 1.000000, 1.000000
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define COL_COUNT 4
int main(int argc, const char * argv[]) {
//double (*temp)[4][COL_COUNT];
double (*temp)[COL_COUNT];// not need "row"
double array1[4][COL_COUNT];
double array2[4][COL_COUNT];

int i,j;
int nCount = 0;
for (i=0; i<4; i++) {//init some data
for (j=0; j<COL_COUNT; j++) {
array1[i][j] = nCount;
nCount++;
}
}
for (i=0; i<4; i++) {//init some data
for (j=0; j<COL_COUNT; j++) {
array2[i][j] = nCount;
nCount++;
}
}
printf("array1 = n");
temp = array1;
for (i=0; i<4; i++) {//printf the array1 data
for (j=0; j<COL_COUNT; j++) {
printf("%6.0lf ",temp[i][j]);
}
printf("n");
}
printf("array2 = n");
temp = array2;
for (i=0; i<4; i++) {//printf the array2 data
for (j=0; j<COL_COUNT; j++) {
printf("%6.0lf ",temp[i][j]);
}
printf("n");
}

return 0;
}

最新更新