1

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

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.