Is there possible to make the code work without changing the main function? I have tried using strcpy() in the push function but it results in segmentation fault (core dumped).
This is the output currently:
ccc ccc ccc
ccc ccc ccc
ccc ccc ccc
The output should be
ccc ccc ccc
bbb bbb bbb
aaa aaa aaa
Code:
struct Node
{
char *data1;
char *data2;
char *data3;
struct Node *next;
};
int main()
{
struct Node *head = NULL;
char strings[3][10];
char *s = "aaa";
for (int i = 0; i < 3; i++)
{
strcpy(strings[i], s);
}
push(&head, strings);
s = "bbb";
for (int i = 0; i < 3; i++)
{
strcpy(strings[i], s);
}
push(&head, strings);
s = "ccc";
for (int i = 0; i < 3; i++)
{
strcpy(strings[i], s);
}
push(&head, strings);
printList(head);
freeList(&head);
}
void push(struct Node **head_ref, char new_data[3][10])
{
/* 1. allocate node */
struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));
/* 2. put in the data */
new_node->data1 = new_data[0];
new_node->data2 = new_data[1];
new_node->data3 = new_data[2];
/* 3. Make next of new node as head */
new_node->next = (*head_ref);
/* 4. move the head to point to the new node */
(*head_ref) = new_node;
}
stringsso of course the result is only the last values copied intostrings. Show yourstrcpyversion if you want help with that. My guess is that you are not allocating memory for thedataXfields before callingstrcpy.strings.char *data1->char data1[100]etc. in the struct definition andnew_node->data1 = new_data[0]->strcpy(new_node->data1, new_data[0])etc.