EXC_BAD_ACCESS与结构

时间:2018-10-22 06:08:05

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

下面的代码创建一个从1〜9的结构数组作为顶点,然后接受顶点所指向的其余部分。例如,如果某人输入1作为主顶点,那么他将允许输入一个图形的多个节点。但是,我目前面临着第三个while循环和最后一个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]);
}

1 个答案:

答案 0 :(得分:1)

您只是忘记了初始化newItem->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];