将char复制到struct指针char

Copy a char to a struct pointer char

本文关键字:char 指针 struct 复制      更新时间:2023-10-16

我有两个结构体和一个变量类型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];
};

当我想更改每本书的标题时

        //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是一个数组,包含id,标题,摘要,作者数量以及名字和姓氏

和上面的代码适用于标题

但是当我尝试使用以下代码

更改作者的名字和姓氏时
        //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);

程序编译,当我运行它,它说"程序不响应"作为一个窗口错误,并关闭…

只使用std::strings(和std::vector<Author>代替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";

您的author变量很可能没有被分配。指针只能指向其他对象,并且需要正确分配以便分配变量(例如:author = new Author)。

Author *au;
au->firstname = "hello" //au is a pointer and cannot hold values, error
au = new Author;
au->firstname = "hello" //valid