1

I have 2 structs and a variable type Book

Book book_struct[100];

typedef struct Book{
  int id;
  char title[256];
  char summary[2048];
  int numberOfAuthors;
  Author * authors;
};

typedef struct Author{
  char firstName[56];
  char lastName[56];
};

when i want to change the title of each book i do

        //title
        char *title_char=new char[parsedString[1].size()+1];
        title_char[parsedString[1].size()]=0;
        memcpy(title_char,parsedString[1].c_str(),parsedString[1].size());

        strcpy(books_struct[z].title, title_char);

where parsedString is an array which contains the id,title,summary,number of authors and a firstname and lastname

and the above code works for title

but when i try to change the author firstname and lastname using the following code

        //author firstname
        char *author_fn_char=new char[parsedString[4].size()+1];
        author_fn_char[parsedString[4].size()]=0;
        memcpy(author_fn_char,parsedString[4].c_str(),parsedString[4].size());

        strcpy(books_struct[z].authors->firstName, author_fn_char);

the program compiles and when i run it it says "Program not responding" as a windows error and closes...

stergosz
  • 5,754
  • 13
  • 62
  • 133
  • This is C that happens to compile on a C++ compiler. Don't use `malloc`. Use `std::string`. Use `std::vector`. Use `std::array`. – chris May 20 '13 at 17:36
  • @chris , so the method i am using to do what i want is outdated? and probably there is a better way to do it? – stergosz May 20 '13 at 17:37
  • 2
    I am not so sure it compiles, given the order of declarations in your first code frament. – Marc Claesen May 20 '13 at 17:37
  • It compiles but when i run it it simply says "Program not Responding" - when i remove the `strcpy` code the program opens without errors – stergosz May 20 '13 at 17:38

2 Answers2

3

Just use std::strings (and std::vector<Author> instead of Authors*):

#include <string>
#include <vector>

struct Book{
  int id;
  std::string title;
  std::string summary;
  std::vector<Author> authors; // authors.size() will give you number of authors
};

struct Author{
  std::string firstName;
  std::string lastName;
};

Book b;
b.title = "The C++ programming Language";
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

Your author variable is most likely not allocated. pointers can only point to other objects, and need to be correctly allocated in order to assign variables(e.g. author = new Author).

Author *au;
au->firstname = "hello" //au is a pointer and cannot hold values, error
au = new Author;
au->firstname = "hello" //valid
Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177