[英]Writing to an array of arrays and displaying the seperate entities in the array of arrays in C
我正在編寫一個基本上有10條街道的代碼,並且在每條街道中都要求用戶提供房屋數量和每座房屋中的孩子數量。 但是,當我嘗試顯示街道工作的數量時,房屋的數量就會顯示,但是房屋中的孩子數量卻沒有。 我還想知道如何增加街道上的孩子數量,例如一條街道上總共有10個孩子(我真的不知道該怎么做)。 我認為問題出在我的for循環中,但是我不確定是什么問題。 代碼如下所示:
int main()
{
int i=0;
int j=0;
int streets[10];
int houses=0;
int KidsInStreets[houses];
for (i=0;i<10;i++)
{
printf("How many houses are there in street %d:\n", i+1);
scanf("%d",&houses);
for (j=0;j<houses;j++)
{
printf("How many kids are there in house number %d, in street number %d:\n", j+1, i+1);
scanf("%d", &KidsInStreets[j]);
}
}
for (i=0;i<10;i++)
{
for (j=0;j<houses;j++)
{
printf("Street:%d House:%d Kids:%d\n", i+1, j+1, KidsInStreets[j]);//Kids in street output and houses output have bugs, such as all the houses in the street need to be displayed, and the kids thing is just not working
}
}
return 0;
}
一個問題是當你做int KidsInStreets[houses];
時, houses
為零int KidsInStreets[houses];
。 但是真正的問題是您只有一個陣列,但是每條街道都需要一個陣列。
嘗試類似:
int* streets[10]; // Notice *
int houses=0;
for (i=0;i<10;i++)
{
printf("How many houses are there in street %d:\n", i+1);
scanf("%d",&houses);
streets[i] = malloc(houses * sizeof(int)); // Allocate array
for (j=0;j<houses;j++)
{
printf("How many kids are there in house number %d, in street number %d:\n", j+1, i+1);
scanf("%d", &streets[i][j]);
}
}
但是問題是,現在您不知道每條街道上有多少棟房屋。 因此,您需要保存該信息。 為此,您可以構造一個結構或一個額外的數組。
額外的數組不是那么優雅,但很容易:
int* streets[10]; // Notice *
int houses_in_street[10];
int houses=0;
for (i=0;i<10;i++)
{
printf("How many houses are there in street %d:\n", i+1);
scanf("%d",&houses);
streets[i] = malloc(houses * sizeof(int)); // Allocate array
houses_in_street[i] = houses;
for (j=0;j<houses;j++)
{
printf("How many kids are there in house number %d, in street number %d:\n", j+1, i+1);
scanf("%d", &streets[i][j]);
}
}
for (i=0;i<10;i++)
{
for (j=0;j<houses_in_street[i];j++)
{
printf("Street:%d House:%d Kids:%d\n", i+1, j+1, streets[i][j]);
}
}
更好的解決方案是使用類似以下的結構:
struct street {
int number;
int houses;
int* kids_in_house;
};
// use it like
struct street streets[10];
void streets()
{
int i=0;
int j=0;
int* streets[10];
int houses_in_street[10];
int houses=0;
for (i=0;i<10;i++)
{
printf("How many houses are there in street %d:\n", i+1);
scanf("%d",&houses);
streets[i] = malloc(houses * sizeof(int)); // Allocate array
houses_in_street[i] = houses;
for (j=0;j<houses;j++)
{
printf("How many kids are there in house number %d, in street number
%d:\n", j+1, i+1);
scanf("%d", &streets[i][j]);
}
}
for (i=0;i<10;i++)
{
for (j=0;j<houses_in_street[i];j++)
{
printf("Total number of presents required for street:%d house:%d\n=
%d\n", i+1, j+1, streets[i][j]);
total_number_of_presents_required=
total_number_of_presents_required+streets[i][j];
}
}
printf("Total number of presents required in the streets
is:%d\n",total_number_of_presents_required);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.