我只是 C 语言的初学者,正在寻找动态数组结构,并遇到了这个 youtube tutorial .
Code使用指针创建动态数组,而不使用像 malloc() 这样的堆内存分配。我只是想知道,这种方法是否可以,或者它可能会成为一个错误,因为内存可以被覆盖?
代码:
#include "stdio.h"
typedef struct S_RacingCar {
char name[8];
int speed;
} RacingCar;
const int MaxCars = 4;
void PrintList() {
printf("List Print...\n");
}
int AddCar(RacingCar *car) {
printf("Enter Name And Speed: ");
char input[16];
fgets( input, 15, stdin);
int ok = 0;
int res = sscanf(input, "%s %d", car->name, &car->speed);
if(res == 2) {
ok = 1;
printf("Added:%s Speed:%d\n\n",car->name,car->speed);
} else {
printf("Sorry, error parsing input\n\n");
}
return ok;
}
int main() {
RacingCar allCars[MaxCars];
int numCars = 0;
char command[16];
char input[16];
while( fgets( input, 15, stdin) ) {
sscanf(input,"%s",command);
if ( strncmp(command, "quit", 4) == 0) {
printf("\n\nBreaking...\n");
break;
} else if ( strncmp(command, "print", 5) == 0) {
PrintList();
} else if ( strncmp(command, "add", 3) == 0) {
if(numCars < MaxCars) {
numCars += AddCar( &allCars[numCars] );
} else {
printf("Sorry List Is Full!!\n\n");
}
}
}
return 0;
}
最佳答案
您的代码中没有动态数组
RacingCar allCars[MaxCars];
这里,数组的最大大小已定义为MaxCars
。可能会让您感到困惑的是,从 main
开始,对数组的引用被发送到其他函数,在这些函数中将值添加到数组中。
要在 C 中创建动态数组,可以使用 malloc
、calloc
或 realloc
。
关于c - 这种在 C 中使用动态数组结构的方法可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52343831/