C语言 使用 strtok、malloc 和 realloc 从字符串中制作一个令牌数组



有一些主题与此部分重叠,但我仍在寻求答案。

标记化部分工作正常,但动态内存分配似乎不是,基于打印循环未注释时的段错误。

free(( 只是检查 free(( 是否有效,而不是成为完成函数的一部分,它返回 NULL,直到它可以返回一些合理的内容。

SEP通常是一个空格。行尾的任何 在到达此处之前都会得到处理。

char ** chunkify(char *line, char *sep)
{
printf("%sn", line);
char **array = malloc(sizeof(char *));        
int token_count = 0;
char *token = NULL;   
token = strtok(line, sep);
while( token != NULL )
{              
printf("t%sn", token);
array = realloc(array,(token_count + 1) * sizeof(char *));      
array[token_count] = malloc(strlen(token) + 1);
strcpy(array[token_count],token);
token = strtok(NULL, sep);
token_count++;
}  
/*
int j;
for ( j=0 ; *(array+j) ; ++j)
{
printf("t%sn", *(array+j));
free(*(array+j)); // just to see if it frees cleanly
}
free(array);
*/
return NULL; // will return array when it's fixed
}

您应该用空指针附加指针数组。否则,不知道数组包含多少个元素。

如果使用的方法不够智能,因为它不报告分配错误,那么函数可以像本演示程序所示一样。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char ** chunkify( char *line, const char *sep )
{
char **array = malloc( sizeof( char * ) );
if ( array )
{
size_t n = 1;
char *token = strtok( line, sep );
while ( token )
{
char **tmp = realloc( array, ( n + 1 ) * sizeof( char * ) );
if ( tmp == NULL ) break;
array = tmp;
++n;
array[ n - 2 ] = malloc( strlen( token ) + 1 );
if ( array[ n - 2 ] != NULL ) strcpy( array[ n - 2 ], token );
token = strtok( NULL, sep );
}
array[ n - 1 ] = NULL;
}
return array;
}
int main(void) 
{
char s[] = "Hello World";
char **array = chunkify( s, " " );
if ( array != NULL )
{
for ( char **p = array; *p; ++p ) puts( *p );
for ( char **p = array; *p; ++p ) free( *p );
free( array );
}       
return 0;
}

程序输出为

Hello
World

最新更新