這是我在C中的第一個編程。在printGrid()函數中,我試圖給2D數組分配一些值,並且2D數組中的其餘點只分配0。一個數組,它按預期工作。但是,當我使用display()函數打印出整個數組時,它無法正常工作,數組中的所有值均爲0.在發佈問題之前,我花了幾個小時來完成搜索和調試這裏。有人可以幫我解決這個問題嗎?謝謝。爲什麼2D數組總是在C中輸出0?
#include <stdio.h>
#include <stdlib.h>
const int max_height = 4;
int height; //the height of pile
int center_x_index, center_y_index; //index of input parameter that is center of the plane
int unstable;
int drop_status;
int *grid[5][5];
int is_stable(int total_param, char *piles[]);
void display(int *grid[5][5]);
/*
Function to print out the 23*23 grid with given number of piles
*/
void printGrid(int total_param, char *piles[])
{
int i, j, k, size, assigned;
size = 5;
for (i = 0; i < size; i++)
{
for (j = 0; j < size; j++)
{
for (k = 1; k < total_param; k = k + 3)
{
if ((atoi(piles[k]) == i) && (atoi(piles[k + 1]) == j))
{
height = atoi(piles[k + 2]);
//find the central pile of the plane and drop a grain of sand onto this pile.
if ((i == j) && i == (size/2))
{
center_x_index = k;
center_y_index = k + 1;
if (drop_status > 0 && is_stable(total_param, piles))
{
drop();
}
}
grid[i][j] = &height; //store value into 2D array
//printf("2D array: %d", *grid[i][j]);
printf("%d", height);
assigned = 1;
break;
}
else
{
assigned = 0;
}
}
if (assigned != 1)
{
height = 0;
grid[i][j] = &height;
printf("%d", 0);
}
}
printf("\n");
}
}
void display(int *grid[5][5])
{
int i, j;
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
printf("%d", *grid[i][j]);
}
printf("\n");
}
}
int main(int argc, char *argv[])
{
printGrid(argc, argv);
printf("\n");
}
因爲'&height'總是相同的值,'grid [i] [j] =&height'不會像你期望的那樣工作。 – ymonad
添加預期發佈的命令行和輸出示例。 ('center =(char)(atoi(argv [center_x_index + 2]) - 4); argv [center_x_index + 2] =&center;':我不認爲它可以正常工作,即使預期會發生什麼。) – BLUEPIXY
請縮進您的代碼並嘗試發佈[MCVE](https://stackoverflow.com/help/mcve),而不是整個程序。此外,[不要使用'atoi'](https://stackoverflow.com/q/17710018/995714) –