2016-03-15 52 views
0

我試圖在C中有一個無限數組來存儲一些數據。我的頭文件stock.h看起來像這樣在C中的靈活數組

#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件物品。但是添加第二項似乎會使整個應用崩潰,而不知道爲什麼。

回答

3

啓用所有警告和對待他們的每一個的錯誤。這樣你就可以發現成員的問題不是自己已經提到的指針。

檢查庫函數的返回值,如mallocrealloc以查找錯誤並正確處理它們。

最後,你會希望交換這兩行:

stock->size++; 
stock->electrodomesticos[stock->size] = t; 
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++; 

否則你的代碼是UBstock->size++ == stock->capacity

+0

編輯要清楚在哪裏添加包括。我希望你不要介意:) –

+0

@DanielJour詛咒,我不介意。謝謝。 – LPs