gpt4 book ai didi

c - 使用链表反向打印字符串

转载 作者:行者123 更新时间:2023-11-30 19:41:41 25 4
gpt4 key购买 nike

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

我目前正在调试我的程序,但我完全陷入困境。我有一种感觉,大部分与内存有关。

/*

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

最佳答案

我看到的一个错误是您使用 strcpy 的方式如下:

strcpy( argv[1], stringBuffer );

它将 stringBuffer 的值复制到 argv[1] 中,您应该以相反的方式执行此操作,如下所示:

strcpy( stringBuffer, argv[1]);

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

关于c - 使用链表反向打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33271598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com