用功能构建结构

时间:2020-01-31 21:16:46

标签: c function struct dynamic malloc

您好,我正在尝试构建一个功能,以根据客户需求为客户搜索汽车。 结构包含:型号,年份,价格。 客户被要求输入他的要求,然后代码调用一个函数,该函数检查结构中是否有适合他的汽车。

我收到“访问冲突读取错误”的错误消息 谢谢!

  #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#define SIZE 10
typedef struct
{
    char model[10];
    float price;
    int year;
}car;

void findCar(car *arr[], int minYear, float maxPrice, char modelWanted, int carAmount);
int main()
{
    int carAmount;
    car* arr;
    puts("How many cars?");
    scanf("%d", &carAmount);
    arr = (car*)malloc(carAmount * sizeof(car));
    if (arr == NULL)
        return -1;
    for (int i = 0; i < carAmount; i++)
    {
        puts("Enter car details, Model, Price,Year");
        scanf("%s%f%d",arr[i].model,&arr[i].price,&arr[i].year);
    }
    char modelWanted[SIZE];
    float maxPrice;
    int minYear;
    puts("Enter wanted model,maximum price and minimum year!");
    scanf("%s%f%d", modelWanted, &maxPrice, &minYear);
    for (int i = 0; i < carAmount; i++)
        printf("Model is: %s, Price is: %.2f, Year is: %d\n", arr[i].model, arr[i].price, arr[i].year);
    findCar(&arr, minYear, maxPrice, modelWanted, carAmount);
    free(arr);
    return 1;
}

void findCar(car *arr[], int minYear, float maxPrice, char modelWanted,int carAmount)
{
    int i, counter = 0;
    for (i = 0; i < carAmount; i++)
        if (((strcmp(arr[i]->model, modelWanted)) == 0) && (arr[i]->year >= minYear) && (arr[i]->price <= maxPrice))
        {
            printf("Model is: %s, Price is: %.2f, Year is: %d\n", arr[i]->model, arr[i]->price, arr[i]->year);
            ++counter;
        }
    printf("We found %d cars for you!", counter);
}

1 个答案:

答案 0 :(得分:1)

您正在传递指向struct数组的指针

car *arr[]

因此,不要像以前那样通过arr[i]->model访问元素,而应该使用(*arr)[i].model访问元素。您使用的方法用于访问struct元素的指针数组,但是您具有指向struct数组的指针。

当然已经注释了char而不是char*也会引起运行时错误,但是您应该为此收到编译器警告。