我在编写循环链表程序的时候出现Process returned -1073741819 (0xC0000005)的情况,
请问是指针的使用出现问题了吗,还是其他的问题呢?
另外ListNode* a[N]; //can I create an array using N?
这个可以以形参N作为输入创建数组吗?
以下是我的代码,谢谢!
#include <stdio.h>
#include <stdlib.h>
//define a node
typedef struct ListNode
{
int val;
struct ListNode* next;
}ListNode;
//construct a linked list Cycle
void 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;
}
//input needed variables
int main()
{
int N, A, B, K;
scanf("%d %d %d %d", &N, &A, &B, &K);
makecycle(N);
}
供参考:
#include <stdio.h>
#include <stdlib.h>
//define a node
typedef struct ListNode
{
int val;
struct ListNode* next;
}ListNode;
//construct a linked list Cycle
void makecycle(int N)
{
int i;
//ListNode* a[N]; //can I create an array using N?
ListNode*a = new ListNode[N];//动态数组
a[0].next = &a[1];//a[1]->next = a[2];
a[0].val = 1;
for(i = 1; i < N-1; i++)
{
a[i].next = &a[i+1];//a[i]->next = a[i+1];
a[i].val = i+1;
}
a[N-1].next = NULL;//a[N]->next = a[1];
a[N-1].val = N; //a[N]->val = N;
ListNode *p=a;
while(p)
{
printf("%d ",p->val);
p = p->next;
}
}
//input needed variables
int main()
{
int N, A, B, K;
scanf("%d %d %d %d", &N, &A, &B, &K);
makecycle(N);
return 0;
}
#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?
for(i = 1; i <= N; i++)
{
a[i] = (ListNode*)malloc(sizeof(ListNode));
}
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, j = 1;
scanf("%d %d %d %d", &N, &A, &B, &K);
ListNode *head = makecycle(N);
while(head && j <= 10) {
printf("%d ", head->val);
head = head->next;
j++;
}
}