将char复制到struct指针char
Copy a char to a struct pointer char
我有两个结构体和一个变量类型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
相关文章:
- 构造函数 (C++) 中的 char 指针参数存在问题
- 将 char 指针传递给接受对 char 数组的引用的函数
- 分配值时,C++ char* 指针上的前递增与后递增
- char指针或char变量的默认值是多少
- 为什么为char指针分配内存不会截断char序列
- 愚蠢的问题:strcat和char指针
- 使用 ctypes 从函数返回字符串C++会给出大的 int,而不是 char 指针
- 打印char指针的Unicode和文本值
- 应对 std::字符串中的 std::<char>指针转换后的向量
- 一系列char指针
- 为什么可以将Char指针变量初始化为字符串,而INT指针变量不能初始化到整数数组
- 将char指针传递给cin和cin.get()
- 在C和C++中,将int值转换为char指针的差异
- std :: cout null char*指针中止该程序
- char指针违反访问权限
- const char指针在结构中声明
- 将字符串转换为 char 指针可以指向的 char 数组/值的最有效方法是什么
- 将Char指针数组传递到C 中的函数
- 获取错误C2440:char []* char*(指针)
- 删除Char指针在destructor中不起作用