2013-05-04 71 views
1

我有我的C語言編寫的程序確實有問題設置一個變量,它停止在該行e->identifiant=0;C,在結構

代碼:

struct Evenement* e=(struct Evenement*)(malloc(sizeof(struct Evenement))); 
e->identifiant=0; 

有:

struct Evenement{ 
int identifiant; 
char titre[100]; 
struct Creneau creneau; 
char lieu[50]; 
char description[500]; 
}; 

你有想法嗎?

+1

'malloc'是否成功?您不需要在C程序中投射返回值。 – 2013-05-04 15:28:26

+0

它如何停止?你會得到分段錯誤嗎?如果@CarlNorum可能在正確的軌道上,malloc沒有成功。在嘗試分配給它之前,你應該檢查'e'是否爲非零(非NULL)。 – 2013-05-04 15:29:37

+0

事實上,在malloc之後e是NULL ... 我不明白爲什麼... Malloc寫入正確...不是? – user1360503 2013-05-04 15:31:20

回答

1

我編譯和運行這個:

#include <stdio.h> 
#include <stdlib.h> 

struct Evenement{ 
int identifiant; 
char titre[100]; 
char lieu[50]; 
char description[500]; 
}; 

int main() 
{ 
    struct Evenement* e=(struct Evenement*)(malloc(sizeof(struct Evenement))); 
    e->identifiant = 0; 
    printf("%d", e->identifiant); 
    return 0; 
} 

,並沒有問題。你能告訴我們什麼是錯誤?


我刪除struct Creneau creneau;線,怎麼一回事,因爲沒有它的描述。這可能是問題嗎?

+0

即使我刪除struct Creneau creneau;問題仍然存在...... – user1360503 2013-05-04 15:39:29

+1

@ user1360503:在您的代碼中,問題不在您顯示的行中;它在程序的其餘部分。您顯示的線條僅僅是檢測到問題的位置。由於內存損壞問題(您可能會遇到這種問題;另一種方法是您已經分配了一個已經吃掉所有可用內存的惡劣陣列),故障的原因往往遠離問題檢測的地方,是使他們難以察覺的特徵之一。 – 2013-05-04 16:09:45

+0

正如@Jonathan所說,問題不在代碼的這一部分。如果你可以分開你的程序中的方法或有問題的東西並單獨測試它們;你將能夠發現問題所在。 – sha1 2013-05-04 20:31:01