c - 访问结构指针数组时出错

标签 c

我正在尝试构建邻接表,但出现以下错误

graph.c:16: 错误:下标值既不是数组也不是指针

我读到当非数组试图被索引时会发生此错误。当我能够直接向其中添加一个元素时(第 58 行:graph[i] = root),请问将结构数组的成员分配给 NODE 的错误是什么?

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 10
struct node{
    int data;
    struct node * link;
};

typedef struct node * NODE;
NODE graph[MAX];
void displayGraph (graph, n){
int i;
NODE cur;
for (i=0;i<n;i++){
    cur = graph[i];
    while(cur != NULL){
        printf("%d ", cur->data);
        }
    }
}

NODE insert (NODE root, NODE temp){
NODE mine;
mine = root;
    if (mine == NULL)
        return root;
    while(mine != NULL){
    mine = mine->link;
    }
mine->link = temp;
return root;
}

main ()
{
int n=0;
int i;
int val;
char * choice;
NODE temp, root;
printf("Enter the number of nodes\n");
scanf("&d", n);
for (i=0;i<n;i++){
    root = NULL;
    while(1){
        printf("Is there an adjacent node?Y:N");
        scanf("%s", choice);
        if(!strcmp(choice, "N"));
            break;
        printf("Enter the adjacent node\n");
        scanf("%d", val);
        temp = malloc(sizeof (struct node));
        temp->data = val;
        temp->link = NULL;
        root = insert(root, temp);
         }
graph[i] = root;
    }
displayGraph (graph, n);
}

最佳答案

您在声明 displayGraph 函数时未指定变量图形的类型。

void displayGraph (graph, n);

由于 graph 是全局声明的,因此从技术上讲,您可以省略 graph 作为此函数的参数。您还需要为变量 n 提供类型,但如果您坚持让 displayGraph 接受图形数组,则更改:

void displayGraph (graph, n){

void displayGraph (NODE graph[], int n){

您的代码还有一些其他问题,但这应该可以解决您所询问的错误。

关于c - 访问结构指针数组时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19600173/

相关文章:

c - 将可变长度的2D数组传递给函数

c++ - 仅使用 8 字节 CAS 无锁? C++

C 结构到 Swift

c - 为什么 VS 2012 中出现此运行时 OpenGL 错误?

c++ - 谁能给我解释一下这个 --kill-at 链接器选项?

c - C 可执行文件错误

c - 分割链表在函数作用域外显示为空

c - 星号( printf ("%s\n",*argv) ) 是什么意思?

c - 声明一个指向内存中地址 0x200 处的整数的指针

我可以以头文件实现中不存在的方式使用结构吗?