使用需知:
这里采用动态分配内存空间,所以使用时有些注意事项详解
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
/*
* &beginBytes nextBytes为空传入beginBytes需为动态开辟的内存地址,否则free崩溃
* beginLength beginBytes的长度
* nextBytes 需要追加的内存数据
* nextLength nextBytes的长度
*@return 状态码
*/
int arrayAppend(char ** beginBytes, char *nextBytes, unsigned int &beginLength, int nextLength)
{
if (*beginBytes == NULL&&nextBytes == NULL)
return -1;
char *tempArray = NULL;
tempArray = (char *)calloc((beginLength + nextLength + 1), sizeof(char));
if (beginLength >0)
{
memcpy(tempArray, *beginBytes, beginLength);
free(*beginBytes); *beginBytes = NULL;
}
memcpy(tempArray + beginLength, nextBytes, nextLength);
beginLength += nextLength;
tempArray[beginLength] = '\0';
*beginBytes = tempArray;
return 0;
}
int main()
{
char *str1[4] = { "Hello ", "Array", " I need it ", "Variable length" };
char *str = "";
unsigned int beginLength = 0;
for (size_t i = 0; i < 4; i++)
{
unsigned int nextLength = strlen(str1[i]);
arrayAppend((char **)&str, str1[i], beginLength, nextLength);
printf("message:%s\n", str );
}
if (str!=NULL)
{
free(str); str = NULL;
}
system("pause");
return 0;
}