【发布时间】:2021-05-01 17:35:42
【问题描述】:
我想接收来自键盘的输入,例如: 输入国家数量:
我的结构是
struct country {
char name[20];
int population;
float area;
float gdp;
char continent[20];
}
如果用户键入 3,我想要其中的 3 个结构。如何申报?
【问题讨论】:
我想接收来自键盘的输入,例如: 输入国家数量:
我的结构是
struct country {
char name[20];
int population;
float area;
float gdp;
char continent[20];
}
如果用户键入 3,我想要其中的 3 个结构。如何申报?
【问题讨论】:
您从用户输入中读取数字,然后在运行时创建相应数量的结构:
#include <stdlib.h>
#include <stdio.h>
struct country {
char name[20];
int population;
float area;
float gdp;
char continent[20];
};
int main(int argc, char *argv[]){
unsigned int count;
scanf("%u", &count); //read count
struct country *countries = calloc(sizeof(struct country), count); //allocate memory for count country structs
countries[0].area = 1.0f; //now you can access the structs like array elements
}
【讨论】: