【发布时间】:2018-08-31 16:38:55
【问题描述】:
我正在尝试创建一个函数,该函数接受一个字符串和一个指向字符串数组的指针和malloc() char 数组的数组,并复制字符串的每个单词。这就是我到目前为止所拥有的,我想我已经接近了,我只是在努力在数组数组上使用malloc()。
int string_parser(char *inp, char **array_of_words_p[])
{
int CurrentChar = 0; //Variable Initialization
char *buffer; //Variable Initialization
/* Allocate memory and check for errors allocating memory */
//Allocate memory to buffer the size of the input string
buffer = (char*)malloc(strlen(inp));
if (buffer == NULL)
{
printf("Error allocating memory..\n");
return -1;
}
/* Move input string into buffer before processing */
for (CurrentChar = 0; CurrentChar < strlen(inp) + 1; CurrentChar++)
{ //For every character in input
if (inp != NULL)
{
//Move input character into buffer
buffer[CurrentChar] = inp[CurrentChar];
}
}
/* Convert string into array of words */
char ** stringbuffer = NULL;
//Convert string to array of words
char * CurrentWord = strtok_s(buffer, " ", *array_of_words_p);
//Variable Initialization
int numspaces = 0;
while (CurrentWord)
{
//Allocate memory for size of string
stringbuffer = (char**)realloc(stringbuffer, sizeof(char**) * ++numspaces);
if (stringbuffer == NULL)
{
return -1;
}
stringbuffer[numspaces - 1] = CurrentWord;
//Reset Current word to null
CurrentWord = strtok_s(NULL, " ", *array_of_words_p);
}
//Reallocate memory to include terminating character
stringbuffer = (char**)realloc(stringbuffer, sizeof(char**) * (numspaces + 1));
stringbuffer[numspaces] = 0;
/* Write processed data into returned argument */
*array_of_words_p = (char**)malloc(sizeof(char**) * (numspaces + 2));
memcpy(*array_of_words_p, stringbuffer, (sizeof(char*) * (numspaces + 2)));
free(stringbuffer);
return numspaces;
}
【问题讨论】:
-
请添加 C/C++ 标签
-
问题/问题是什么?
标签: c arrays string malloc buffer