我被要求创建一个用户可以添加汽车的程序,我将不得不保存汽车的品牌,颜色等。然后我必须展示它们,并展示那些销售额更高的产品。我考虑过创建一个结构并保存所有内容,问题是,我不知道用户将输入多少辆汽车。
如何动态增加结构保存值?我想做类似的事情:
struct car{
int Bhp;
char Brand[25];
char color[25];
int sales;
float weight;
};
然后:
struct car car1;
struct car car2;
但我必须动态增加"汽车的数量"因为用户会添加越来越多。有什么办法可以吗?请以简单的方式解释,因为我还是C初学者。非常感谢你。
答案 0 :(得分:3)
最初使用malloc()
:
struct car *p = malloc(sizeof(struct car);
现在您可以添加一个汽车细节。现在,如果您想增加汽车的数量,那么请使用realloc()
并根据您要添加的汽车详细信息的数量分配更大的内存。
struct car *temp = realloc(p,sizeof(struct car) *n);
if(temp != NULL)
p = temp;
检查以下代码:
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
struct car{
int Bhp;
char Brand[25];
char color[25];
int sales;
float weight;
};
int main(void) {
int n;
struct car *temp = NULL;
struct car *p = malloc(sizeof(struct car));
p->Bhp = 100;
strcpy(p->Brand,"audi");
strcpy(p->color,"red");
p->sales = 200;
p->weight = 250.90;
printf("%d %s %s %d %5.2f\n",p->Bhp,p->Brand,p->color,p->sales,p->weight);
printf("Enter number of cars\n");
scanf("%d",&n);
temp = realloc(p,sizeof(struct car) *(n+1));
if(temp == NULL)
{
printf("Reallocation failed\n");
return 0;
}
p = temp;
p[1].Bhp = 100;
strcpy(p[1].Brand,"benz");
strcpy(p[1].color,"green");
p[1].sales = 300;
p[1].weight = 240.90;
printf("%d %s %s %d %5.2f\n",p[1].Bhp,p[1].Brand,p[1].color,p[1].sales,p[1].weight);
// The rest of the data can be filled similarly
return 0;
}
答案 1 :(得分:3)
只需这样做,首先声明n
,它将是car
&#39>数组中元素的数量
int n;
并初始化
n = 0;
现在声明一个指针
struct car *car = NULL;
现在说你有1
car
,然后将1
分配给n
,
struct car *temp = realloc(car, n * sizeof(struct car));
if (temp != NULL)
car = temp;
现在您可以使用n-th
访问car[n - 1]
元素,第一个元素是car[0]
,因此您必须减去一个元素。如果n
更多,那么增加car
后,只需free(car)
完成后使用它。
您不需要第一个malloc
,因为当您将NULL
传递给realloc
时,其行为就像malloc
。
答案 2 :(得分:1)
最常见的方法是使用指向结构的指针和动态内存分配。
答案 3 :(得分:-1)