[英]C linked list incompatible pointer type
struct list_node {
int value;
struct list_node *next;
};
struct linked_list {
int size;
struct list_node *head;
};
void print_linked_list(struct linked_list *list){
struct linked_list *current = list;
while(current != NULL){
printf("%d ", current->head->value);
current = current->head->next;
}
}
我必須定義一個 function 來打印出一個鏈表,但我收到一條錯誤消息,說“指針類型不兼容”。 我知道問題出在“current = current->head->next;” 但我怎樣才能做到這一點?
current
是一個struct linked_list*
,但current->head->next
是一個struct list_node*
。
struct linked_list
和struct list_node
是兩個不同的不相關結構,盡管它們相似。
您不能將指針分配給不同的類型,因此會出現錯誤消息incompatible pointer type 。
你可能想要這個:
void print_linked_list(struct linked_list* list) {
struct list_node* current = list->head;
while (current != NULL) {
printf("%d ", current->value);
current = current->next;
}
}
function
void print_linked_list(struct linked_list *list){
struct linked_list *current = list;
while(current != NULL){
printf("%d ", current->head->value);
current = current->head->next;
}
}
沒有意義。
在這份聲明中
current = current->head->next;
指針current
的類型為struct linked_list *
而表達式current->head->next
的類型為struct list_node *
。
看來你的意思
void print_linked_list( const struct linked_list *list )
{
if ( list != NULL )
{
for ( const struct list_node *current = list->head; current != NULL; current = current->next )
{
printf( "%d ", current->value );
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.