2012-05-27 148 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])