【问题标题】:Initializing a pointer to an array in C在 C 中初始化指向数组的指针
【发布时间】:2015-11-13 18:01:45
【问题描述】:

我遇到了一些指针问题(我对编码很陌生)。在 main() 中,我试图通过 InitWorkerArray 初始化我的员工名册,这样我就可以打印它(该功能不包括在下面),但每当我尝试 CodeBlocks 时,它就会关闭。我查找了很多关于指针的信息,但似乎很少有人处理数组/结构,所以任何帮助将不胜感激。不幸的是,我确定我有很多错误。

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

【问题讨论】:

  • 您收到的错误信息是什么?你的问题的重点是什么?如果您只是在寻找代码审查,请查看 codereview.stackexchange.com 问答
  • 我认为您在 main 末尾缺少一个 }。另外,你应该把 void 放在 main 的参数括号中。
  • 您将 pRoster 设置为 malloc 块,然后奇怪地将其在下一行设置为 NULL。这不会做任何有用的事情!
  • 不要在问题中重新输入程序,而是复制并粘贴实际代码。这将确保您不会引入与您实际遇到的问题无关的任何其他错误。在您的情况下,main 函数没有结束,并且您显示的代码无法构建。
  • @marco 我没有收到任何错误消息,CodeBlocks 实际上只是停止工作

标签: c arrays pointers struct initialization


【解决方案1】:

最大的问题在于这两行:

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 调用会崩溃。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-11
      • 1970-01-01
      • 2015-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-19
      • 1970-01-01
      相关资源
      最近更新 更多