简体   繁体   中英

Array of pointers to structures filled using function in C

I am trying to make a program that fills an array of pointers to struct but uses a function to do so. I believe I am doing something wrong with the pointers because I need to preserve the address of b1 at the end of add(); The program compiles but I get a runtime error.

This is my code:

#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;
}

You are pretty close: you need to pass a pointer to pointer, and invert the assignment:

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++
}

The call to add() should look like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM