我正在编写一个函数,它接收一个字符串并从中提取标记,并将它们存储在堆栈中。有一个叫currentToken的变量,以内存开头只有1个字符:
char *currentToken = ( char * )malloc( sizeof( char ) );
随着 token 的形成,currentToken 通过 realloc 扩展以容纳新字符。每次 currentToken 完成时,都会通过引用将其添加到堆栈中。然后,我尝试“重置”它(就像我将它设置为一个空字符串一样)释放它的内存并再次分配它。它会破坏堆栈中先前包含的数据吗?如果是这样,我该如何解决这个问题?提前致谢。
堆栈被实现为一个结构,并且从一开始就被初始化:
typedef struct stackOfStrings {
char **array;
int numberOfElements;
} StackOfStrings;
/* Initializes the stack of strings: */
void initializeStackOfStrings( StackOfStrings *sPtr )
{
sPtr->numberOfElements = 0;
sPtr->array = ( char ** )malloc( 1 * sizeof( char * ) );
}
/* Inserts str at the top the stack of strings, returning 1 if it succeeds, or 0
otherwise: */
int pushOnStackOfStrings( StackOfStrings *sPtr, char *string )
{
int length = string_length( string );
++( sPtr->numberOfElements );
sPtr->array = realloc( sPtr->array, ( sPtr->numberOfElements ) * sizeof( char * ) );
if ( sPtr->array == NULL )
{
return 0;
}
*( sPtr->array + ( sPtr->numberOfElements - 1 ) ) = ( char * )malloc( length * sizeof( char ) );
*( sPtr->array + ( sPtr->numberOfElements - 1 ) ) = string;
return 1;
最佳答案
试试这个
void initializeStackOfStrings( StackOfStrings *sPtr )
{
sPtr->numberOfElements = 0;
sPtr->array = NULL;
}
...
sPtr->array[sPtr->numberOfElements - 1] = ( char * )malloc( (length+1) * sizeof( char ) );
strcpy(sPtr->array[sPtr->numberOfElements - 1], string);
关于c - 关于在 C 中为字符串变量分配的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21652012/