gpt4 book ai didi

c - 如何以正确的方式将结构的数组传递给我的函数?

转载 作者:太空宇宙 更新时间:2023-11-04 06:12:08 25 4
gpt4 key购买 nike

我试图将一个结构的数组传递给一个函数,但是当 i 变为 1 时它给我一个错误,acces violation。这是我的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>

typedef struct {
int locuri;
int putere;
char marca[50];
char culoare[50];
int an_fabricatie;
}automob;

void aloca(automob **autos, int n)
{
*autos = (automob*)malloc(sizeof(automob)*n);
if (autos == NULL) {
exit(1);
}
}

void read_autos(const char* filename, automob **A, int *n)
{
FILE *f_in = fopen(filename, "r");
int i = 0, aux;
if (f_in == NULL) {
printf("Nu s-a gasit fisierul!");
_getch();
exit(0);
}
fscanf(f_in, "%d", n);
aloca(A, *n);
while (i < (*n)) {
fscanf(f_in, "%d", &A[i]->locuri);
fscanf(f_in, "%d", &A[i]->putere);
fscanf(f_in, "%s", &A[i]->marca);
fscanf(f_in, "%s", &A[i]->culoare);
fscanf(f_in, "%d", &A[i]->an_fabricatie);
i++;
}
}

void main()
{
int n;
automob *A;
read_autos("autos.in", &A, &n);
_getch();
}

我认为指针 A 没有正确分配,但我真的不知道。你有什么想法?因为当我在 main 函数中编写它时这有效,但如果我在另一个函数(如 read_autos)中正确它则不起作用。

最佳答案

A[i] -> locuri 表示(* A[i]).locuri;如果 A 是指向 automob 的指针数组,这就有意义了;但事实并非如此。你想要 (* A)[i].locuri。其他领域依此类推。

    fscanf(f_in, "%d", &(* A)[i].locuri);
fscanf(f_in, "%d", &(* A)[i].putere);
fscanf(f_in, "%s", (* A)[i].marca);
fscanf(f_in, "%s", (* A)[i].culoare);
fscanf(f_in, "%d", &(* A)[i].an_fabricatie);

你写了什么:

+------+     +-------+     +--------------------------------------------+
| A -----> | A[0] -----> | locuri | putere | marca | culoare | an_fab |
+------+ | | +--------------------------------------------+
+-------+ +--------------------------------------------+
| A[1] -----> | locuri | putere | marca | culoare | an_fab |
| | +--------------------------------------------+
+-------+ +--------------------------------------------+
| A[2] -----> | locuri | putere | marca | culoare | an_fab |
| | +--------------------------------------------+
+-------+ +--------------------------------------------+
| A[3] -----> | locuri | putere | marca | culoare | an_fab |
| | +--------------------------------------------+
+-------+

你想要什么:

+------+     +-------+         +--------------------------------------------+
| A -----> | * A -----> [0] | locuri | putere | marca | culoare | an_fab |
+------+ +-------+ +--------------------------------------------+
[1] | locuri | putere | marca | culoare | an_fab |
+--------------------------------------------+
[2] | locuri | putere | marca | culoare | an_fab |
+--------------------------------------------+
[3] | locuri | putere | marca | culoare | an_fab |
+--------------------------------------------+

关于c - 如何以正确的方式将结构的数组传递给我的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54035103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com