2015-11-13 106 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