gpt4 book ai didi

c - 段错误背后的原因是什么?

转载 作者:行者123 更新时间:2023-12-02 09:06:04 24 4
gpt4 key购买 nike

我无法在任何调试器中调试以下代码,因为它显示“在启动程序期间以段错误 SIGEGV 结束”

这是用于查找图是否是二分图的代码。

#include <stdlib.h>
#define ll long long

ll queue[1000000000];
ll last=0;
ll top=0;

int qempty()
{
if(top==last) return 1;
else return 0;
}

void emptyq()
{
top=0;
last=0;
}
void enqueue(long long x)
{
queue[top++] = x;
}
void dequeue()
{
queue[last++];
}

这里我定义了队列。以下是Graph的函数。

struct node
{
ll vertex;
struct node* next;
};

struct node* createNode(ll v)
{
struct node *newnode = malloc(sizeof(struct node));
newnode->vertex = v;
newnode->next = NULL;
return newnode;
}

struct Graph
{
ll numVertices;
struct node** adjLists;
};

struct Graph *createG (ll vertices)
{
struct Graph *G = malloc(sizeof(struct Graph));
G->numVertices = vertices;
G->adjLists = malloc(vertices*sizeof(struct node*));
for(int i=0;i<vertices;i++) G->adjLists[i]=NULL;
return G;
}

void add(struct Graph* G, ll src, ll dest)
{
struct node* newnode = createNode(dest);
newnode->next = G->adjLists[src];
G->adjLists[src] = newnode;

newnode = createNode(src);
newnode->next = G->adjLists[dest];
G->adjLists[dest] = newnode;

}

这是宽度优先搜索中检查同一层之间的边缘的函数。

ll BU(struct Graph *G, ll src, ll *color)
{
color[src] = 1;
emptyq();
enqueue(src);
while (qempty);
{
ll u = queue[last];
dequeue;
struct node *y = G->adjLists[u];
while(y)
{
if(color[y->vertex]==-1)
{
color[y->vertex] = 1-color[u];
enqueue(y->vertex);
}
else if (color[y->vertex] == color[u]) return 0;

y=y->next;
}
}
return 1;

}

ll B(struct Graph *G)
{
ll x = G->numVertices;
ll *color = malloc(x*sizeof(long long));
for (ll i = 0; i < x; ++i) color[i] = -1;

for (ll i = 0; i < x; i++)
if (color[i] == -1)
if (BU(G,i,color)==0)
return 0;

else return 1;
}

这是主要功能。我在 main 函数的第一行添加了一个断点,但它拒绝继续。

int main()
{
ll t;
scanf("%lld",&t);
printf("%lld",t);
while(t--)
{
ll V,E;
scanf("%lld %lld",&V,&E);
printf("%lld %lld",V,E);
struct Graph *G = createG(V);
while(E--)
{
ll x,y;
scanf("%lld %lld",&x,&y);
add(G,x,y);
}
if(B(G)==1) printf("Yes\n");
else printf("No\n");

}
return 0;
}

最佳答案

您可能想要减小其大小:

ll queue[1000000000];

更合理的值,例如1024

关于c - 段错误背后的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58452927/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com