[英]array of pointers to structures
我想了解我的代碼是否正確。 我需要聲明一個指向結構的指針的數組,創建一個新的結構並分配值並打印它們。 在我看來,我沒有正確地聲明指針數組。 我需要知道我在做什么錯。 謝謝,我得到了這個編譯錯誤:錯誤:未聲明“ people”(此功能首次使用),並且我嘗試插入結構數據* list;。 進入主要,但沒有用
char *book[] = { "x", "y", "z",};
int number[] = { 1, 2, 3};
struct data = { char *bookname; int booknumber;};
function(char *x, int y)
{
static int count;
struct data *list[3];
//creating a new struct
list[count] = (struct data*) malloc( sizeof(struct data) );
//assigning arguments
list->bookname = x;
list->booknumber = y;
count++;
}
int main()
{
struct data *list[3];
int i;
for(i = 0; i < 3; i++)
{
function(book[i], number[i]);
printf("name: %c number: %d", list[i]->bookname, list[i]->booknumber);
}
由於需要數組,因此需要聲明數組:
char *book[] = { "x", "y", "z",};
int number[] = { 1, 2, 3};
另一個問題是
list = (struct data*) malloc( sizeof(struct data) );
//assigning arguments
list[count]->bookname = ...
在這里, list
總是只有一個元素。 因此,如果count
是0
以外的任何0
,那么您將超出范圍訪問數組!
請更改以下代碼
// declaring array of pointers to structs //
struct data *list;
//not compiling
//struct data *list[3]; ---> There is no problem with this statement.
//creating a new struct
list = (struct data*) malloc( sizeof(struct data) ); ---> //This statement should compilation error due to declaration of struct data *list[3]
至
struct data *list[100]; //Declare a array of pointer to structures
//allocate memory for each element in the array
list[count] = (struct data*) malloc( sizeof(struct data) );
我想你應該寫:
char *book[] = { "x", "y", "z"};
因為在您的情況下,您聲明了一個char數組,並用指針填充了它,這實際上沒有任何意義。
在上面的代碼行中,它僅表示“聲明指針數組”。
希望能有所幫助...
這些是程序中的錯誤
struct data = { char *bookname; int booknumber;};
“ =”不應該在那里
list = (struct data*) malloc( sizeof(struct data) );
list[count]->bookname = x;
list[count]->booknumber = y;
在這里,您正在為單個列表創建空間,因此您不能執行list [count]->書名,它應該是list-> bookname。 與書號相同
並且列表是本地功能,您不能在主目錄中訪問它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.