【问题标题】:EXC_BAD_ACCESS with struct带有结构的 EXC_BAD_ACCESS
【发布时间】:2018-10-22 06:08:05
【问题描述】:

以下代码从 1~9 创建一个结构数组作为顶点,然后它接受顶点指向的其余部分。例如,如果有人输入 1 作为主顶点,他将允许为一个图输入多个节点。但是,我目前面临第三个 while 循环和最后一个循环的问题。对于这一部分,它应该检测到下一个为 NULL 并退出,但它给了我一个 EXC_BAD_ACCESS 错误。

#include <stdio.h>
#include <stdlib.h>

struct node{
    int data;
    struct node* next;
};

int main(){
    struct node *G[10];
    for (int i = 1; i < 10; i++)
    {
        G[i]= malloc(sizeof(struct node));
        G[i]->data = i;
        G[i]->next = NULL;
        printf("%i\n", G[i]->data);
    }
    int input = 10;
    int vertixBeingModi=1;
    printf("Please enter your vertix you want to modify? \n");
    scanf("%i", &vertixBeingModi);
    while(vertixBeingModi != 0){
        while (input != 0){
            printf("Please enter the edges ? \n");
            scanf("%i", &input);
            struct node* cursor;
            struct node* newItem;
            cursor = G[vertixBeingModi];
            if (input == 0){
                break;
            }
            while(cursor->next != NULL )
            {
                cursor = cursor->next;
            }
            newItem = malloc(sizeof(struct node));
            cursor->next = newItem;
            newItem->data = input;
            cursor = G[vertixBeingModi];
        }
        printf("Please enter your vertix you want to modify? \n");
        scanf("%i", &vertixBeingModi);
        input = 1;
        if (vertixBeingModi == 0){
            break;
        }
    }
    int array[10];
    struct node* tempDegree;
    int counter = 0;
    for(int x = 1; x < 10; x++){
        tempDegree = G[x];
        if(tempDegree->next == NULL){
            continue;
        }else{
            while(tempDegree->next != NULL ){
                counter = counter + 1;
                tempDegree = tempDegree->next;
            }
            array[x] = counter;
            counter = 0;
        }
    }
    printf("%d\n", array[1]);
}

【问题讨论】:

  • 我推荐你learn how to debug your code。更具体地说,学习如何使用调试器在崩溃发生时捕捉崩溃,并在代码中找到它发生的位置。
  • 在一个完全不同的注释 for (int i = 1; i &lt; 10; i++) 索引为 0
  • 还要考虑你做一些事情的顺序。例如,如果cursor 是空指针,cursor-&gt;next != NULL &amp;&amp; cursor != NULL 将失败并导致您取消对 cursor 的引用。
  • 您的代码看起来非常复杂。程序应该做什么?

标签: c linked-list exc-bad-access


【解决方案1】:

你只是忘了初始化newItem-&gt;next

while (cursor->next != NULL)
  {
    cursor = cursor->next;
  }
  newItem = malloc(sizeof(struct node));
  newItem->next = NULL;    // <<<<<<<<<<<< add this line
  cursor->next = newItem;
  newItem->data = input;
  cursor = G[vertixBeingModi];

【讨论】:

  • 谢谢!有用!但是为什么我们需要添加该行?当我为它分配内存时,newitem->next 应该是 NULL 吗?试图理解。
  • @NeverSleepAlwaysCode malloc分配的内存没有初始化。顺便说一句,在您的 for 循环开始时,您可以正确初始化 next 指针。
  • @NeverSleepAlwaysCode No. malloc 返回一块内存,但它的内容是不确定的。如果要分配和初始化新的内存为零,请使用calloc。 (并且,学会检查scanfalwaysreturn...)
猜你喜欢
  • 2012-01-22
  • 2011-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多