因此,我正在尝试编写一个 C 程序,该程序从命令行接收一个字符串,并遍历该字符串并使用链表将其反转。它目前不工作,我不知道为什么。到目前为止,我只用 C++ 编程,所以 C 中的细微差别真的让我陷入了循环。有人可以帮我找出程序中的错误吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct st_CharNode
{
char theChar;
struct st_CharNode *next;
} CharNode;
void reverseIt( char *stringbuffer );
int main( int argc, char *argv[] )
{
char *stringBuffer;
// Check number of user supplied arguments.
if( argc != 2 )
{
fprintf( stderr, "usage: %s string. This reverses the string "
"given on the command line\n" );
exit( -1 );
}
// Copy the argument so we can make changes to it
stringBuffer = malloc( strlen(argv[1]) );
strcpy( argv[1], stringBuffer );
// Reverse the string
reverseIt( stringBuffer );
// Print the reversed string
printf( "the reversed string is '%s'\n", *stringBuffer );
return 0;
}
// Build a linked list backwards, then traverse it.
void reverseIt( char *stringbuffer )
{
CharNode *head, *node;
char *scan, *stop;
// initialize local vars
head = node = NULL;
// find the start and end of the string so we can walk it
scan = stringbuffer;
stop = stringbuffer + strlen(stringbuffer) + 1;
// walk the string
while (scan < stop)
{
if (head == NULL)
{
head = malloc( sizeof(CharNode*) );
head->theChar = *scan;
head->next = NULL;
}
else
{
node = malloc( sizeof(CharNode*) );
node->theChar = *scan;
node->next = head;
head = node;
}
scan++;
}
// Re-point to the buffer so we can drop the characters
scan = stringbuffer;
// Traverse the nodes and add them to the string
while( head != NULL )
{
*scan = head->theChar;
free( head );
node = head->next;
head = node;
scan++;
}
// Release head
free( head );
}
当我 ./a.out 并在命令行上输入像“Hello”这样的字符串时,我的当前输出是“反转的字符串是'(null)'”。