![](/img/trans.png)
[英]C Program crashes when accessing specific array element of struct field
[英]C program crashes when trying to refer to struct array
我正在嘗試制作一個簡單的數據庫程序,但是當我到達這一行時
int idSearch(product* itens, int id) {
int i = 0;
for(i; i < size; i++) {
if(itens[i].id == id) //<=== This line
return i;
}
return ITEM_NOT_FOUND;
}
程序停止響應。 在程序開始時將size設置為全局變量
FILE* flog;
FILE* db;
FILE* sizef;
int size = 100;
該函數由
void newProduct(product* itens, char name[64], int id, float price) {
int pos = idSearch(itens, 0);
if(idSearch(itens, id) != ITEM_NOT_FOUND) {
printf("Erro, o produto ja existe");
return;
}...
項目定義為
itens = (product*) calloc(sizeof(product), size);
而product是這樣定義的struct
typedef struct{
char name[64];
int id;
float price;
int amount;
} product;
首先,我認為問題在於我沒有使用->
運算符,但是當我嘗試編譯器時,它說不正確。
我在Windows 7 x64上的GCC編譯器中使用Code :: Blocks
**編輯:整個代碼可以在這里找到: http : //hastebin.com/atulajubar.tex
希望很快能收到答案,謝謝
**編輯:您在錯誤地調用calloc() 。 簽名是: void *calloc(size_t nelem, size_t elsize);
首先要給它大小, 然后是元素數。 切換一下,看看問題是否解決。
另外,在調用(FIX:之后) itens = (product*) calloc( size, sizeof(product) );
,請務必在執行此操作后檢查itens不是NULL。 如果calloc無法為您提供合適的內存,它將返回一個NULL指針,我相信。 進行檢查,因為如果返回NULL,那就是您的問題。
一種良好,簡便,可移植的檢查方法是:
if(!itens){
fprintf(stderr, "Error! Could not allocate memory!\n");
exit(1);
}
另外,如WhozCraig所建議的那樣,請確保您的代碼包含#include <stdlib.h>
,這是其手冊頁上對calloc()的要求。
這是錯誤的:
if((db = fopen(DB_PATH, RB))==NULL)
{
if((db = fopen(DB_PATH, RWB))==NULL)
{
exit(1);
}
else
{
itens = (product*) calloc(sizeof(product), size);
fwrite(itens, sizeof(product), size, db);
rewind(db);
}
}
fread(itens, sizeof(product), size, db);
如果當前工作目錄中有一個DB_PATH文件,則第一個fopen()
將成功執行,並且items
分配將永遠不會發生。 只有當該文件沒有找到,但隨后成功創建將items
包含一個有效的分配,假定calloc
工作。
else
條件應刪除:
// note calloc parameter order addressed.
itens = calloc(size, sizeof(product));
if (itens == NULL)
{
perror("Failed to allocate items.");
exit(EXIT_FAILURE);
}
if((db = fopen(DB_PATH, RB))==NULL)
{
if((db = fopen(DB_PATH, RWB))==NULL)
exit(EXIT_FAILURE);
fwrite(itens, sizeof(product), size, db);
rewind(db);
}
fread(itens, sizeof(product), size, db);
還有大量錯誤檢查需要處理,但是無論如何都需要解決。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.