I'm new on C and embedded systems and I need to reallocate a variable type char which is an array by definition.
I have:
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
Tried to use some examples as
(realloc(payLoad, sizeof(char *) * chrNum))
But my program blocks in this line.
You have payload
defined as a char
array, and you can't resize an array defined at compile time. You need to define it as a pointer so you can dynamically allocate memory:
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;