作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在将链接列表中的字符数组的内容复制到常规字符数组时遇到问题。我遇到了段错误问题,但我不确定原因。
我创建的程序在链表中的字符数组只有一个字符时可以工作,但是当它大于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时,就会产生段错误。请告诉我在这个程序中需要纠正什么。谢谢。
最佳答案
#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/
我是一名优秀的程序员,十分优秀!