为了简单起见:可以看到下面有两个函数声明。
void tableau_initialize(int Rn, int slack_num, int Cn, int A[Rn][Cn], int B[Rn], int C[Cn+1], float ***A_tableau, float **obj_array);
void array_debug(int row, int col, float *A);
在 main() 函数中,这两个函数是这样调用的:
int A[5][6] = {
{10, 11, 12, 0, 0, 0},
{0, 0, 0, 14, 12, 13},
{1, 0, 0, 1, 0, 0},
{0, 1, 0, 0, 1, 0},
{0, 0, 1, 0, 0, 1}
};
int B[5] = {0, 0, 1, 1, 1};
int C[7] = {0, 0, 0, 0, 0, 0, 1};
float **Z;
float *optimal;
tableau_initialize(5, 2, 6, A, B, C, &Z, &optimal);
array_debug(1, 6, optimal);
在第一个函数 tableau_initialize() 中,可以看到我如何初始化 obj_array 一维数组,如下所示:
//Create 1-D dynamic array:
*obj_array = malloc(sizeof(float) * 6);
//Result array copy:
for(int i = 0; i < Rn; i++) {
(*obj_array)[i] = (float)B[i];
} (*obj_array)[Rn] = 0;
array_debug(1, 6, *obj_array);
array_debug()只是一个数组打印调试函数,代码如下。
void array_debug(int row, int col, float *A) {
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
printf("%f\t", *(A+i*col+j));
}
printf("\n");
}
printf("\n");
}
问题:为什么在 main() 函数中打印的 array_debug 显示动态数组 *optimal 已用零填充,但在 tableau_initialize() 中显示 *optimal 是一个非 1 维数组零值?
提前非常感谢您!
使用 指向数组的指针
void array_print(size_t rows, size_t cols, int (*arr)[cols])
{
for(size_t row = 0; row < rows; row++)
{
for(size_t col = 0; col < cols; col++)
printf("%d ", arr[row][col]);
printf("\n");
}
}
void array_init(size_t rows, size_t cols, int (*arr)[cols])
{
for(size_t row = 0; row < rows; row++)
for(size_t col = 0; col < cols; col++)
arr[row][col] = rand() % 100;
}
int main(void)
{
int A[5][6] = {
{10, 11, 12, 0, 0, 0},
{0, 0, 0, 14, 12, 13},
{1, 0, 0, 1, 0, 0},
{0, 1, 0, 0, 1, 0},
{0, 0, 1, 0, 0, 1}
};
size_t rows, cols;
srand(time(NULL));
cols = rand() % 20;
rows = rand() % 30;
array_print(5, 6, A);
printf("------------------------\n");
int (*B)[cols] = malloc(rows * sizeof(*B));
if(B)
{
printf("rows = %zu, cols = %zu\n", rows, cols);
array_init(rows, cols, B);
array_print(rows, cols, B);
free(B);
}
}