2012-05-27 149 views
-1

我试图使曲线这个方案仅仅是在我 声明的结构的指针数组,其保持顶点的地址初始阶段 *顶点[20]是一个阵列,其元素都是类型为struct node的地址*它将包含图的节点地址。阵列结构指针误差的

#include<stdio.h> 
#include<stdlib.h> 
struct node { 
    int data; 
    struct node *links[10]; 
}; 
struct node *create_node(int); 
void create_vertices(struct node **); 
int main() 
{ 
    struct node *vertices[20]; 
    int d, i, choice; 
     *vertices[0]=(struct node *)malloc(sizeof(struct node)*20); 
     create_vertices (&vertices); 
} 

struct node *create_node(int data) 
{ 
    int i; 
    struct node *temp = (struct node *)malloc(sizeof(struct node)); 
    temp->data = data; 
    for (i = 0; i < 10; i++) 
     temp->links[i] = NULL; 
    return temp; 
} 

void create_vertices (struct node **v) 
{ 
int i,choice; 
i=0; 
    printf("enter choice\n"); 
    scanf("%d", &choice); 
    while (choice == 1) { 
     printf("enter data\n"); 
     scanf("%d", &d); 
     vertices[i] = create_node(d); 
     i++; 
     printf("enter choice\n"); 
     scanf("%d", &choice); 
    } 
} 

编译上面的代码给我下面的错误

bfs.c: In function ‘main’: 
bfs.c:13:21: error: incompatible types when assigning to type ‘struct node’ from type ‘struct node *’ 
bfs.c:14:9: warning: passing argument 1 of ‘create_vertices’ from incompatible pointer type [enabled by default] 
bfs.c:8:6: note: expected ‘struct node **’ but argument is of type ‘struct node * (*)[20]’ 
bfs.c: In function ‘create_vertices’: 
bfs.c:35:16: error: ‘d’ undeclared (first use in this function) 
bfs.c:35:16: note: each undeclared identifier is reported only once for each function it appears in 
bfs.c:36:3: error: ‘vertices’ undeclared (first use in this function) 

程序发出错误的下面一行

struct node *vertices[20]; 
*vertices[0]=(struct node *)malloc(sizeof(struct node)*20); 

什么是在这种声明的危害。 我声明了一个类型为struct node的指针数组*我也应该给它们一些内存。

+0

滴在左值星号。该类型应该是一个指针,而不是一个节点。顶点[0] **是一个指针。也删除演员。 – wildplasser

+0

@wildplasser我有一个困惑这里怎么会顶点[1]被保存,因为如果我把所有的内存顶点[0]我所要做的是创建一个顶点数组[0],顶点[1],顶点[ 2],顶点[3]等我试图使用malloc的相同 –

+0

您可以删除整个malloc()线。顶点[]是一个由20个指针组成的数组。 create_vertices()函数会给指针一个值(通过调用malloc()加上一些赋值) – wildplasser

回答

0

主:

create_vertices (&vertices); 

应该是:

create_vertices (vertices); 

另外:这将是更安全,让create_vertices()函数知道数组的大小是什么。我不应该允许i指数超过这个大小。

更新:在主,除去行:

*vertices[0]=(struct node *)malloc(sizeof(struct node)*20); 

顶点[]是在自动存储器20(未初始化)指针的数组( “在栈上”)。

的create_vertices()函数将得到的指针的值。 (通过调用malloc()和结果赋给顶点[I])