簡體   English   中英

如何在C中將結構的指針設置為一個值?

[英]How to set a struct's pointer to a value in C?

鑒於:

struct phoneNum{
   int phoneNumber;
   struct number *next;
};

struct phoneNum numbers [50];

for(y=0; y < 50; y++){
   numbers[y].phoneNumber = 0;
   numbers[y].next = -1;
}

如何將結構的指針設置為值? 我一直在嘗試將其設置為-1,但是在嘗試編譯時出現錯誤。 最終,我需要使該指針指向另一個phoneNum結構。 我試圖形成所有這些結構的基於數組的鏈接列表。

1)由於next是一個指針,因此您可以分配數字[y] .next = NULL

2)在您提到“下一步,指向另一個phoneNum結構”的問題中,則應修改該結構

struct phoneNum
{
   int phoneNumber;
   struct phoneNum *next;
};

將'numbers [y] .next'設置為ptr的值,並且NULL是可接受的值:

   numbers[y].next = NULL;

-1不是ptr的有效值。

您正在嘗試將一個int分配給一個struct number * ,這就是您遇到的錯誤。 嘗試numbers[y].next = (struct number *)(-1); 代替。

但是這種指針的使用是不規則的。 “未設置”的指針應設置為NULL ,而不是您從口袋里掏出來的某個隨機數。

// to construct a linked list you should add link pointer with a same type of your structure
struct phoneNum{
   int phoneNumber;
   struct phoneNum *next;
};

struct phoneNum numbers [50];

for(y=0; y < 50; y++){
   numbers[y].phoneNumber = 0;
// a pointer must be set to NULL, do not set to int "-1"
   numbers[y].next = NULL;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM