所以这是代码,我无法理解。我无法理解的是如何进入结构城镇"来自结构县。此外,我不知道如何在结构城镇写作以及如何访问它们。
#include <stdio.h>
#include <string.h>
struct town {
char name[64];
unsigned number;
};
struct country {
char name[64];
struct town capital;
struct town *towns;
unsigned number_of_towns;
};
int main() {
struct country countries[5];
for (int i = 0; i < 5; i++) {
printf("Name of country: ");
scanf("%s", countries[i].name);
scanf("%s", countries->towns->name); //this is what i try.
}
getchar();
getchar();
return 0;
}
答案 0 :(得分:2)
struct town
类型的变量?struct town v ;
v.name[i] --> ith charcter of `name`
v.number
scanf("%s",v.name);
scanf("%u",&v.number);
如果你使用指针struct town *
,你需要一些东西,以便你可以指向它。您需要收集一些可用于存储信息的变量。
struct town capital;// it doesn't need to point to anyone.
struct town* towns; // I need variable(s) of type struct town so that I can point to it.
towns= malloc(sizeof (struct town)* AS_MANY_AS_YOU_NEED);
//假设您分配4
您需要访问它们。
所以你做了什么?
您可以像这样访问每个struct town类型变量
town[i]
然后您可以像我之前显示的那样访问它们。
当然没有。你可以像
一样 towns = malloc(sizeof (struct town));
像towns[0]
或*(towns+0)
或*towns
分配内存以存储来自免费存储空间的内容。
好的,所以你在towns
中分配了一些更多的变量,可以像towns[i]
和
它是
名称可以像towns[i].name
一样访问。
号码可以在towns[i].number
特定城镇的name
字符towns[i].name[i]
struct country {
char name[64]; //countries[i].name
struct town capital; //countries[i].capital.name or countries[i].capital.number
struct town *towns; // (countries[i]->towns[i]).name or ...
unsigned number_of_towns;
} countries[5];
答案 1 :(得分:0)
请尝试此代码可以帮助您。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct town {
char name[64];
unsigned number;
};
struct country {
char name[64];
struct town capital;
struct town *towns;
unsigned number_of_towns;
};
int main() {
struct country countries[5];
struct town *twn;
for (int i = 0; i < 5; i++) {
printf("Name of country: ");
scanf("%s", countries[i].name);
twn = malloc(sizeof(struct town));
printf("Name of town 0: ");
scanf("%s", twn->name);
countries[i].towns = twn;
}
printf("*** Print Countries ***\n");
for (int i = 0; i < 5; i++) {
printf("Name of country: %s\n", countries[i].name);
printf("Name of town 0: %s\n", countries[i].towns->name);
}
for (int i = 0; i < 5; i++) {
free(countries[i].towns);
}
getchar();
getchar();
return 0;
}
测试
Name of country: one
Name of town 0: onetown
Name of country: two
Name of town 0: twotown
Name of country: three
Name of town 0: threetown
Name of country: four
Name of town 0: fourtown
Name of country: five
Name of town 0: fivetown
*** Print Countries ***
Name of country: one
Name of town 0: onetown
Name of country: two
Name of town 0: twotown
Name of country: three
Name of town 0: threetown
Name of country: four
Name of town 0: fourtown
Name of country: five
Name of town 0: fivetown