我正在尝试创建一个函数,它接受一个字符串和一个字符串数组的指针,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;
}
答案 0 :(得分:0)
//Allocate memory to buffer the size of the input string buffer = (char*)malloc(strlen(inp));
输入字符串的大小包含终止\0
,因此您需要:
buffer = malloc(strlen(inp)+1);
//Convert string to array of words char * CurrentWord = strtok_s(buffer, " ", *array_of_words_p);
将*array_of_words_p
滥用于上下文保存变量是不明智的,因为这需要对其进行适当的初始化。更好:
char *context, *CurrentWord = strtok_s(buffer, " ", &context);
…
CurrentWord = strtok_s(NULL, " ", &context);
//Allocate memory for size of string stringbuffer = (char**)realloc(stringbuffer, sizeof(char**) * ++numspaces);
它可能不会受到伤害(由于指针大小相等),但sizeof(char**)
严格来说是错误的,因为字符串数组的元素属于{{ 1}}。正确的:
char *
stringbuffer = realloc(stringbuffer, sizeof (char *) * ++numspaces); … stringbuffer = realloc(stringbuffer, sizeof (char *) * (numspaces + 1));
您可以免除这种不必要的复制,并通过以下方式替换上述内容来避免访问未分配的内存 /* 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);
:
stringbuffer[numspaces+1]
除此之外,您的功能可以正常工作,可以像:
一样调用 *array_of_words_p = stringbuffer;