gpt4 book ai didi

c - 如何在C中将链表中的字符复制到数组中?

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

我在将链接列表中的字符数组的内容复制到常规字符数组时遇到问题。我遇到了段错误问题,但我不确定原因。

我创建的程序在链表中的字符数组只有一个字符时可以工作,但是当它大于1时就不起作用。主要问题出现在第62行(“array[index] = p -> 单词[计数]")。我尝试使用 strcpy 将其每个索引复制到字符数组中,但这也产生了一个错误,内容如下:“传递‘strcpy’的参数 2 使指针来自整数而不进行强制转换”。但是,当我使用赋值语句时,我只是遇到段错误。我不知道为什么,因为我觉得我已经创建了足够的内存,应该能够保存数组链表的内容。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct node
{
char word[100];
struct node *next;
} ListNode;

int main ()
{
ListNode * head = NULL;
ListNode * tail = NULL;

for (int count = 0; count < 5; count++)
{
ListNode * temp = malloc (sizeof (*temp));

strcpy(temp -> word, "Hi");
temp -> next = NULL;

if (tail == NULL)
{
head = temp;
tail = temp;
}
else
{
tail->next = temp;
tail = temp;
}
}

char array[999]; // array that will hold the characters in the linked list

ListNode * p = head; //position of the current node
int count;
int index = 0;


// while p is still a node in the list
while(p != NULL)
{
if((int) strlen(p -> word) > 1) // checks if the string is longer than one character
{
count = 0; // initializes count as 0

while(count < (int) strlen(p -> word)) // counts how many characters are in the string
{
array[index] = p -> word[count]; // assings the words into charater array
count++; // increments the count
index++; // changes the index
}
}
else
{
array[index] = p -> word[0]; // copies p-word to array
index++; // changes the index in the array
p = p -> next;
}
}

return 0;
}

正如前面提到的,只要链表中的字符数组只有1,程序就可以工作,但是当数字大于1时,就会产生段错误。请告诉我在这个程序中需要纠正什么。谢谢。

最佳答案

  • 简化你的循环; for 循环允许您将循环机制保持在一行上
  • 避免特殊情况;单字符字符串没有什么特别的
<小时/>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct node
{
char word[100];
struct node *next;
} ListNode;

int main ()
{
ListNode * head = NULL;
ListNode * tail = NULL;
ListNode * p ;
int count;
int index ;
char array[999]; // array that will hold the characters in the linked list

for (count = 0; count < 5; count++)
{
ListNode * temp = malloc (sizeof *temp);

strcpy(temp->word, "Hi");
temp->next = NULL;

if (!tail) { head = temp; tail = temp; }
else { tail->next = temp; tail = temp; }
}

count=0;
for(p=head;p; p=p->next) { // walk the linked list

for(index=0; p->word[index]; index++) { // walk the string
array[count++] = p->word[index];
}

}
array[count++] = 0; // terminate

printf("%s\n", array);
return 0;
}

关于c - 如何在C中将链表中的字符复制到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58682434/

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