C中的灵活数组

Flexible array in C

我想在 C 中使用无限数组来存储一些数据。我的头文件 stock.h 看起来像这样

#ifndef STOCK_H
#define STOCK_H

typedef struct {
    char* id;
    char* descripcion;
    int precio;
} tAppliance;

typedef struct {
    int cantidad;
    tAppliance electrodomestico;
} tElectroStock;

typedef struct {
    int size;
    int capacity;
    tElectroStock *electrodomesticos;
} tStock;

void tstock_init(tStock *stock);

void tstock_add(tStock *stock, tAppliance item, int cantidad);

#endif

我的stock.c文件

#include <stdio.h>
#include "stock.h"

void tstock_init(tStock *stock) {
    stock->size = 0;
    stock->capacity = 10;
    stock->electrodomesticos = malloc(sizeof(tElectroStock) * stock->capacity);
}

void tstock_add(tStock *stock, tAppliance item, int cantidad) {
    if(stock->size >= stock->capacity) {
        stock->capacity = stock->capacity * 2;
        stock->electrodomesticos = realloc(stock->electrodomesticos, sizeof(tElectroStock) * stock->capacity);
    }
    tElectroStock t;
    t.cantidad = cantidad;
    t.electrodomestico = item;
    stock->size++;
    stock->electrodomesticos[stock->size] = t;  
}

最后是我的主要功能

#include <stdio.h>
#include "stock.h"

int main(int argc, char **argv)
{
    tStock t; // Creamos nuestra variable de stock
    tstock_init(&t); // Iniciamos el stock
    tAppliance item;
    item.descripcion = "Television SONY";
    item.id = "apeid9";
    item.precio = 20;
    tstock_add(&t, item, 1);
    tstock_add(&t, item, 1);
}

正如您在我的主要功能中看到的那样,我尝试向 tStock 添加 2 个项目。但是添加第二项似乎使整个应用程序崩溃,不知道为什么。

启用所有警告,并将每一个警告都视为错误。这样你就可以发现成员不是你自己已经提到的指针的问题。

检查 mallocrealloc 等库函数的 return 值是否有错误并适当处理。

最后,您需要交换这两行:

stock->size++;
stock->electrodomesticos[stock->size] = t;  

-Wall 编译你会收到警告:

test.c: In function ‘tstock_init’:
test.c:634:5: warning: implicit declaration of function ‘malloc’ [-Wimplicit-function-declaration]
     stock->electrodomesticos = malloc(sizeof(tElectroStock) * stock->capacity);
     ^
test.c:634:32: warning: incompatible implicit declaration of built-in function ‘malloc’
     stock->electrodomesticos = malloc(sizeof(tElectroStock) * stock->capacity);
                                ^
test.c: In function ‘tstock_add’:
test.c:640:9: warning: implicit declaration of function ‘realloc’ [-Wimplicit-function-declaration]
         stock->electrodomesticos = realloc(stock->electrodomesticos, sizeof(tElectroStock) * stock->capacity);
         ^
test.c:640:36: warning: incompatible implicit declaration of built-in function ‘realloc’
         stock->electrodomesticos = realloc(stock->electrodomesticos, sizeof(tElectroStock) * stock->capacity);

添加到 stock.c:

#include <stdlib.h>

您还必须如下切换指令:

stock->electrodomesticos[stock->size] = t; 
stock->size++;

否则当stock->size++ == stock->capacity

时你的代码是UB