When I use the Code::Blocks,I want to create a doubly Linked List.
And I want to use an array to create the nodes whose type are struct*.
I suspect this is where the bug comes from.
And also I don't know that: if I give an Variable N to create a[N], will it be wrong?
And the compiler gives me result of 0 error nd 0 warning, but it returns -1073741819 (0xC0000005).
Do you know where is the wrong place? Thank you in advance!
here are my codes
#include <stdio.h>
#include <stdlib.h>
//define a node
typedef struct ListNode
{
int val;
struct ListNode* next;
}ListNode;
//construct a linked list Cycle
ListNode *makecycle(int N)
{
int i;
ListNode* a[N]; //can I create an array using N?
a[1]->next = a[2];
a[1]->val = 1;
for(i = 2; i < N; i )
{
a[i]->next = a[i 1];
a[i]->val = i;
}
a[N]->next = a[1];
a[N]->val = N;
return a[1];
}
//input needed variables
int main()
{
int N, A, B, K;
scanf("%d %d %d %d", &N, &A, &B, &K);
ListNode *head = makecycle(N);
while(head) {
printf("%d ", head->val);
head = head->next;
}
}
CodePudding user response:
as @Eugene Sh. says, the a[]
is an array of uninitilized pointers.
so I added
for(i = 1; i <= N; i )
{
a[i] = (ListNode*)malloc(sizeof(ListNode));
}
and it runs now
so I see that if I give an Variable N to create a[N], it will not be wrong.
and returning -1073741819 (0xC0000005) maybe a problem of not giving a place to the pointer,
or not initilazing the pointer.
CodePudding user response:
You are constructing a[]
as such,
then you are assigning the non-existent garbage data values, which will result in undefined behaviour. Then the auto
variable a[]
goes out-of-scope, and if it hasn't crashed, you've just written some random place in the memory and returned an uninitialized value. With malloc
initializing the pointers, this program is much better behaved,
This will return the pointer to a[1]
, and all other values are memory leaks because all other values of a
are out-of-scope when the function returns. You are probably looking for something like this,
You might do this by initializing pointers soon after you create them. You actually don't need an a[]
at all, you could do this in-place by using pointers to struct ListNode
:
- keeping
head
at 0; - having
tail
be the last one you've constructed; - having
before_tail
link up totail
; - when you are done, link
tail
tohead
to complete the cycle.