使用链接列表反向打印字符串

时间:2015-10-22 00:40:44

标签: c list debugging data-structures

我构建了一个程序,它从命令行获取一个字符串,并使用链接列表反向打印它。

我目前正在调试我的程序而且我完全陷入困境。我有一种感觉,大多数都与记忆有关。

/*

Takes a string from the command line.  
Makes a linked-list out of it in reverse order.  
Traverse it to construct a string in reverse.  
Clean up (release memory).
*/

#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 );   
}

1 个答案:

答案 0 :(得分:0)

我看到的一个错误是你正在使用这样的strcpy:

strcpy( argv[1], stringBuffer );

将stringBuffer的值复制到argv [1]中,你应该反过来这样做,如下所示:

strcpy( stringBuffer, argv[1]);

有关详细信息,请参阅strcpy的手册页:http://linux.die.net/man/3/strcpy