【问题标题】:Array of pointers to structures filled using function in C指向使用 C 中的函数填充的结构的指针数组
【发布时间】:2016-11-04 22:25:40
【问题描述】:

我正在尝试编写一个程序来填充指向 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;
}

【问题讨论】:

    标签: c pointers structure


    【解决方案1】:

    你已经很接近了:你需要将一个指针传递给指针,并反转赋值:

    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
    

    【讨论】:

      猜你喜欢
      • 2018-11-03
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 2013-04-18
      • 1970-01-01
      相关资源
      最近更新 更多