这是我无法理解的代码。我无法理解的是如何从结构县访问结构“城镇”。我也不知道如何在 structure town 中编写以及如何访问它们。
#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;
}
最佳答案
如何获取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;//不需要指向任何人。
struct town* 城镇;//我需要 struct town 类型的变量,以便我可以指向它。
towns= malloc(sizeof (struct town)* AS_MANY_AS_YOU_NEED);
//假设你分配 4
您需要访问它们。
那你是做什么的?
您可以像这样访问每个 struct town 类型变量
town[i]
然后您就可以像我之前展示的那样访问它们。
我是否需要总是分配超过 1 个元素?
当然不是。你可以有这样的东西
towns = malloc(sizeof (struct town));
像这样访问它 towns[0]
或简单地 *(towns+0)
或 *towns
什么是分配?
分配内存以存储空闲内存中的内容。
帮帮我更多!!
好的,所以你在 towns
中分配了更多变量,其中第 i 个可以像 towns[i]
和
是
name 可以像
towns[i].name
一样访问。number 可以在
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];
关于c - 如何从第二个访问第一个结构-c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41400070/