【发布时间】:2020-03-18 19:26:13
【问题描述】:
在运行代码时,我检查指针是否已分配足够的内存,或者它是否保持为 NULL,但它可以分配我们想要的全部内存量。我们将 C11 与 Clion 一起使用。
第一部分代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "LS_allegro.h"
#define MAX_CHAR 100
typedef struct {
char name[MAX_CHAR];
char escuderia[MAX_CHAR];
int dorsal;
int reflejos;
int c_fisica;
int temperamento;
int gest_neumaticos;
}DatosPiloto;
typedef struct {
char type[26];
int vel;
int acc;
int cons;
int fiab;
}Pieza;
typedef struct {
char name_cat[26];
Pieza *pieza;
int num_piezas;
}Categorias;
int main 和函数调用:
int main (int argc, char **argv) {
char sel[MAX_CHAR];
int opt = 0;
int error = 0, datosok = 0;
// Opcion 1
DatosPiloto datosPiloto;
Categorias *categorias;
if (argc == 5) {
error = abreFichero(argv);
}
else {
printf("Error. El programa tiene que recibir 4 argumentos.");
error = 1;
}
if (error == 0) {
leerArchivos(argv, &categorias);
...
...
argc 是一个整数,始终为 5,**argv 是 clion 中导入文件的指针,其中 [0] 是第一个文件,[4] 是最后一个文件。
而功能是:
void leerArchivos (char **argv, Categorias **categorias) {
FILE *Piezas;
FILE *GPs;
FILE *Corredores;
FILE *Base;
int num_categorias = 0, lineas_leer = 0;
int j = 0, i = 0, cat_count = 0;
char basura;
Piezas = fopen(argv[1], "r");
GPs = fopen(argv[2], "r");
Corredores = fopen(argv[3], "rb");
Base = fopen(argv[4], "rb");
fscanf(Piezas, "%d", &num_categorias);
printf("%d\n", num_categorias);
*categorias = (Categorias *) malloc(num_categorias * sizeof(Categorias));
if (*categorias == NULL || sizeof(categorias) < num_categorias * sizeof(Categorias)) {
printf("ERROR! Memory not allocated or smaller that desired.\n");
}else {
...
...
【问题讨论】:
-
sizeof不会告诉您如何分配 mch 内存。没有标准的方法可以找出答案。使用malloc,您要么至少获得所需的字节数,要么获得NULL。而sizeof(categorias)是指针的大小,不管是否分配给它以及分配多少内存。