realloc char数组c语言arm
realloc char array c language arm
我是 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,根据定义它是一个数组。
我有:
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;