[英]passing array of structure pointer to a function
我正在編寫一個程序,我必須將一組結構指針傳遞給主體中的函數,如下所示
struct node *vertices[20];
create_vertices (&vertices,20);
功能的實現是這樣的事情
void create_vertices (struct node *vertices[20],int index)
{
}
在這里我必須傳遞一個索引為20的結構指針數組,我在主管外做的聲明如下我
void create_vertices(struct node **,int);
但是,每次編譯代碼時,我只會在這三行中出現問題
bfs.c:26:6: error: conflicting types for ‘create_vertices’
bfs.c:8:6: note: previous declaration of ‘create_vertices’ was here
bfs.c: In function ‘create_vertices’:
bfs.c:36:15: error: incompatible types when assigning to type ‘struct node’ from type ‘struct node *’
我無法理解我該怎么做。 我想要做的是:
代碼必須在C上,我在Linux上測試它。 有人能指出我嗎?
該類型&vertices
呼叫create_vertices(&vertices, 20)
是不是你的想法。
它是指向結構的指針數組的指針:
struct node *(*)[20]
並不是
struct node **
降&
呼叫而且你可以重新開業。
編譯(在Mac OS X 10.7.4上使用GCC 4.7.0):
$ gcc -O3 -g -std=c99 -Wall -Wextra -Wmissing-prototypes -c x3.c
x3.c: In function ‘func1’:
x3.c:16:9: warning: passing argument 1 of ‘create_vertices’ from incompatible pointer type [enabled by default]
x3.c:7:10: note: expected ‘struct node **’ but argument is of type ‘struct node * (*)[20]’
$
代碼:
struct node { void *data; void *next; };
void make_node(struct node *item);
void func1(void);
void create_vertices(struct node **array, int arrsize);
void create_vertices(struct node *vertices[20], int index)
{
for (int i = 0; i < index; i++)
make_node(vertices[i]);
}
void func1(void)
{
struct node *vertices[20];
create_vertices(&vertices, 20);
}
刪除&
,代碼編譯干凈。
正如您所寫: struct node *vertices[20];
聲明一個指向節點的指針數組。 現在,如果要創建一個更改其元素的函數,則應聲明一個將此類數組作為參數的函數:
void create_vertices(struct node *arr[20], int size)
或者因為在這種情況下可以省略大小,所以最好將其聲明為:
void create_vertices(struct node *arr[], int size)
注意,這個函數可以這樣調用: create_vertices(vertices, 20);
這使得該函數( arr
)的第一個參數指向該數組的第一個元素。 您可以在此功能中更改此數組,並且更改將在外部可見。
假設你有函數void foo(struct node *ptr)
改變了ptr
指向的node
。 當你聲明struct node *ptr;
並傳遞給這個函數: foo(ptr);
,它可以更改此node
對象,並且更改在外部可見,但它無法更改傳遞的指針ptr
本身。 當您需要更改函數內的指針以便在外部可以看到更改時,這就是將指針地址傳遞給函數並將指針指向指針時的情況。
在create_vertices
的原型中,第一個參數是指向結構的指針。 在定義中,第一個參數是指向結構的20個指針的數組。
原型和定義都必須相同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.