2015-11-13 147 views
0

我有一些指針問題(我對編碼非常陌生)。在main()中我試圖通過InitWorkerArray初始化我的員工名單,這樣我就可以打印它(該函數不包含在下面),但每當我嘗試CodeBlocks時都會關閉。我查了很多關於指針的信息,但似乎很少處理數組/結構,所以任何幫助,將不勝感激。不幸的是,我確信我有很多錯誤。初始化一個指向C中數組的指針

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

typedef struct workerT_struct { 
    char *pName; //employee name 
    int maxName; //size, in chars, of the memory buffer to store emp name 
    char *pTitle; //employee title 
    int maxTitle; //size of the memory buffer created to store title 
} workerT; 
void initWorkerArray(workerT *pList, int siz); 
void prntWorker(workerT *pList, int siz, int indx); 

int main() 
{ 
    int maxRoster = 8; 
    workerT *pRoster; 
    pRoster = (workerT*)malloc(sizeof(workerT) * maxRoster); 
    pRoster = NULL; 
    initWorkerArray(pRoster, maxRoster); 
return 0; 
} 
void initWorkerArray(workerT *pList, int siz) { 

    pList[0].maxName = 32; 
    pList[0].maxTitle = 50; 
    pList[0].pName = malloc(sizeof(char) * maxName); 
    pList[0].pTitle = malloc(sizeof(char) * maxTitle); 

    strcpy(pList[0].pName, "Buggy, Orson"); 
    strcpy(pList[0].pTitle, "Director/President"); 

    strcpy(pList[1].pName, "Czechs, Imelda"); 
    strcpy(pList[1].pTitle, "Chief Financial Officer"); 

    strcpy(pList[2].pName, "Hold, Levon"); 
    strcpy(pList[2].pTitle, "Customer Service"); 
    return; 
} 
void prntWorker(workerT *pList, int siz, int indx) { 
    int i = indx; 
     printf("%s, ", pList[i].pName); 
     printf("%s, ", pList[i].pTitle); 
     printf("\n\n"); 
    return; 
} 
+0

你得到的錯誤信息是什麼?問題的重點是什麼?如果您只是在尋找代碼審查,請檢查codereview.stackexchange.com問答 –

+0

我認爲您在main的結尾缺少了a}。另外,你應該把void放在main的參數括號中。 –

+3

您將pRoster設置爲malloc塊,然後奇怪地將它設置在下一行爲NULL。這不會做任何有用的事情! – Richard

回答

2

最大的問題是在這兩條線:

pRoster = (workerT*)malloc(sizeof(workerT) * maxRoster); 
pRoster = NULL; 

在您分配內存並將其分配給pRoster第一線,但隨後在第二天線重新分配pRoster是空指針。在initWorkerArray函數中稍後解除空指針的引用將導致undefined behavior。這個UB最可能的結果是崩潰。

另外,in C you should not cast the result of malloc或返回void *的任何其他函數。如果包含正確的頭文件,這不會造成任何問題,但是您仍然不應該這樣做。

2

此外,在initWorkerArray中,調用strcpy(pList [1] ...)和strcpy(pList [2] ...),pList [1] .pName等從未分配過,因此這些strcpy電話會崩潰。

+0

這是非常愚蠢的我,但謝謝你! – peo965