Nik
Nik

Reputation: 25

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

Upvotes: 1

Views: 42

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

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

Upvotes: 2

Related Questions