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;
}
}
我必須定義一個函式來列印出一個鏈接串列,但我收到一條錯誤訊息,說“不兼容的指標型別”。我知道問題出在“current = current->head->next;” 但我怎樣才能做到這一點?
uj5u.com熱心網友回復:
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;
}
}
uj5u.com熱心網友回復:
功能
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 );
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/415836.html
標籤:
