c - 这种在 C 中使用动态数组结构的方法可以吗?

标签 c dynamic-arrays

我只是 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 中创建动态数组,可以使用 malloccallocrealloc

关于c - 这种在 C 中使用动态数组结构的方法可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52343831/

相关文章:

c++ - vector vector 的段错误

保存整数值的 C++ 字符数组

c - C中的结构体数组

c - 二叉树结构实现的问题

c - C 中的链表操作 Read Proof

c - 提取特定范围的位并在 C 中找到它们之间的零数

c 将结构传递给更新方法

excel - 将excel的新动态数组功能与VBA相结合

c - 插入到c中的动态二维数组

c - 信号量在 OS X 上不断崩溃