C语言中的灵活数组

时间:2016-03-15 15:12:24

标签: c dynamic-arrays

我试图在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个项目。但是添加第二项似乎会使整个应用程序崩溃,并且不知道为什么。

2 个答案:

答案 0 :(得分:3)

启用所有警告,并将其中的每一个都视为错误。通过这种方式,您可以发现该成员不是自己已经提到的指针的问题。

检查mallocrealloc等库函数的返回值是否存在错误并正确处理。

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

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

答案 1 :(得分:0)

-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