簡體   English   中英

使用C中的函數填充的結構的指針數組

[英]Array of pointers to structures filled using function in C

我正在嘗試制作一個程序,該程序填充指向struct的指針數組,但是使用一個函數來這樣做。 我相信我的指針做錯了,因為我需要在add()的末尾保留b1的地址; 該程序可以編譯,但是出現運行時錯誤。

這是我的代碼:

#include <stdio.h>
#include <stdlib.h>

char *title[]= {"a", "b", "c"};
int bookNum[]= {1, 2, 3};

typedef struct
{
  char *BookName;
  int BookNumber;
}Book;

static void add(Book *b1, char *book, int num)
{
  static int count = 0;
  /*trying to create new book struct and give the right address*/
  Book *b2 = (Book*) malloc (sizeof(Book));
  b2 = b1;

  b2->BookName = book;
  b2->BookNumber = num;
  count++
}

int main(int argc, char **argv)
{
  Book *books[3];

  for  (int i = 0; i < 3; i++)
    add(books[i], title[i], bookNum[i]);    


  for (int i = 0; i < 3; i++)
    printf("Name: %s --- Age: %i \n", books[i]->BookName, books[i]->BookNumber);

  return 0;
}

您非常接近:您需要將指針傳遞給指針,然后反轉分配:

static void add(Book **b1, char *book, int num) // Take pointer to pointer
{
  static int count = 0;
  /*trying to create new book struct and give the right address*/
  Book *b2 = malloc (sizeof(Book)); // Don't cast malloc, C lets you do it
  *b1 = b2; // <<== Assign to what's pointed to by b1, not to b2

  b2->BookName = book;
  b2->BookNumber = num;
  count++
}

add()的調用應如下所示:

add(&books[i], title[i], bookNum[i]);    
//  ^
//  |
// Pass the address of the pointer

暫無
暫無

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

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