首页 > 解决方案 > 使用函数构建结构

问题描述

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

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

  #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);
}

标签: cfunctionstructdynamicmalloc

解决方案


您正在将指针传递给结构数组

car *arr[]

所以不要像你一样访问元素arr[i]->model,你应该使用(*arr)[i].model. 您使用的方法是访问指向结构元素的指针数组,但您有指向结构数组的指针。

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


推荐阅读