Nic*_*ter 1 c malloc linked-list
我有这段代码,我正在处理添加一些字符串 aa 链接列表以反转列表。但我收到段错误错误。
segmentation fault: 11 是我在编译器上看到的。
可能会涉及内存分配问题,但目前这并不重要。
还有一个警告字符常量对于它的类型来说太长了。我不确定这意味着什么。
我怎么解决这个问题?
#include <stdio.h>
#include <stdlib.h>
struct Node {
char *data[100];
struct Node *next;
};
static void reverse(struct Node **head_ref) {
struct Node *prev = NULL;
struct Node *current = *head_ref;
struct Node *next = NULL;
while (current != NULL) {
// Store next
next = current->next;
// Reverse current node's pointer
current->next = prev;
// Move pointers one position ahead.
prev = current;
current = next;
}
*head_ref = prev;
}
void push(struct Node **head_ref, char new_data) {
struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(struct Node *head) {
struct Node *temp = head;
while (temp != NULL) {
printf("%s ", temp->data);
temp = temp->next;
}
}
int main() {
/* Start with the empty list */
struct Node *head = NULL;
push(&head, "hi");
push(&head, "hello");
push(&head, "mello");
printf("Given linked list\n");
printList(head);
reverse(&head);
printf("\nReversed Linked list \n");
printList(head);
getchar();
}
Run Code Online (Sandbox Code Playgroud)
小智 6
在您的 push 函数中,您似乎在传递 achar当您打算传递 a 时char *。
此外,您正在new_data为同一函数中的数组赋值。
如果您将data变量更改为char *仅类型,则可以进行此分配。这意味着您之前需要根据每个字符串的大小分配必要的内存,但正如您所提到的,现在这并不重要。
这是带有这 2 个更改的代码,经过测试可以正常工作;
#include <stdio.h>
#include <stdlib.h>
struct Node {
char * data;
struct Node* next;
};
static void reverse(struct Node** head_ref)
{
struct Node* prev = NULL;
struct Node* current = *head_ref;
struct Node* next = NULL;
while (current != NULL) {
// Store next
next = current->next;
// Reverse current node's pointer
current->next = prev;
// Move pointers one position ahead.
prev = current;
current = next;
}
*head_ref = prev;
}
void push(struct Node** head_ref, char * new_data)
{
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(struct Node* head)
{
struct Node* temp = head;
while (temp != NULL) {
printf("%s ", temp->data);
temp = temp->next;
}
}
int main(){
/* Start with the empty list */
struct Node* head = NULL;
push(&head, "hi");
push(&head, "hello");
push(&head, "mello");
printf("Given linked list\n");
printList(head);
reverse(&head);
printf("\nReversed Linked list \n");
printList(head);
getchar();
}
Run Code Online (Sandbox Code Playgroud)
希望这有帮助!