我是C和嵌入式系统的新手,我需要重新分配一个可变类型char,按定义是数组。

我有:

char payLoad[1];
chrNum = 16 +
    strlen("\"message\":")          +
    strlen(strMsg)                  +
    strlen(", \"status":")          +
    strlen(strStatus)               +
//here I need to realloc my payLoad to message size chrNum
// after using this information i need to come back the array to 1 again


试图使用一些例子作为

  (realloc(payLoad, sizeof(char *) * chrNum))


但是我的程序在这一行中阻塞了。

最佳答案

您已将payload定义为char数组,并且无法在编译时调整数组的大小。您需要将其定义为指针,以便可以动态分配内存:

char *payLoad = NULL, *temp;
chrNum = 16 +
    strlen("\"message\":")          +
    strlen(strMsg)                  +
    strlen(", \"status":")          +
    strlen(strStatus);
temp = realloc(payLoad, chrNum + 1);
if (temp == NULL) {
    perror("realloc failed");
    exit(1);
}
payload = temp;

关于c - 重新分配char数组c语言臂,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35419709/

10-13 03:09