在C中初始化指向数组的指针

Initializing a pointer to an array in C

我在使用指针时遇到了一些问题(我对编码还很陌生)。在 main() 中,我试图通过 InitWorkerArray 初始化我的员工名单,这样我就可以打印它(下面不包括该功能),但每当我尝试 CodeBlocks 时,它就会关闭。我查阅了很多关于指针的信息,但似乎很少有处理 arrays/structs 的,因此我们将不胜感激。不幸的是,我确定我有很多错误。

#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;
}

最大的问题在这两行:

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 * 的任何其他函数。如果包含正确的头文件,这不会造成任何问题,但您仍然不应该这样做。

此外,在 initWorkerArray 中,strcpy(pList[1]...) 和 strcpy(pList[2]...)、pList[1].pName 等的调用从未分配,因此这些strcpy 调用会崩溃。