[英]incompatible types in assignment of ‘char’ to ‘char [100]’
I am doing a review for school and I'm having a problem writing a function that creates a new struct and return a pointer to it. 我正在为学校做一个评论,我在编写一个创建新结构并返回指针的函数时遇到问题。
// Review program
#include <iostream>
#include <stdlib.h>
#include <string>
#include <stdio.h>
using namespace std;
Book * makeBook(char * title, char * authorFName, char * authorLName, int numOfPages);
struct PersonName {
char first[50];
char last[50];
};
struct Book {
char title[100];
PersonName author;
int numOfPages;
};
int main()
{
char test[100] = "Hello, world";
cout << test << endl;
return 0;
}
Book * makeBook(char * title, char * authorFName, char * authorLName, int numOfPages)
{
Book newBook;
newBook.title = *title;
Book* pBook = &newBook;
return pBook;
}
The error, in the title, occurs because of newBook.title = *title;
标题中的错误是因为
newBook.title = *title;
. 。 Any help wpuld be appreciated.
任何帮助wpuld表示赞赏。
It's correct, you cannot copy an array using the assignment operator. 没错,你不能使用赋值运算符复制数组。
Try strcpy(newBook.title, title)
, or a variant with a maximum length. 尝试
strcpy(newBook.title, title)
或具有最大长度的变体。
strcpy
is found in <string.h>
or <cstring>
. strcpy
位于<string.h>
或<cstring>
。
*title is of type char. * title的类型为char。 You are trying to assign that to an array of char.
您正在尝试将其分配给char数组。 Hence the error.
因此错误。
You cannot assign arrays with the assignment operator. 您不能使用赋值运算符分配数组。 You need to perform a copy.
您需要执行副本。 For instance:
例如:
strcpy(newbook.title, title);
It's rather hard to know why you are eschewing the C++ standard string container and using C constructs for your strings. 很难知道为什么要避开C ++标准字符串容器并为字符串使用C结构。
There are more problems with your code. 您的代码存在更多问题。 Not the least of which is where you return the address of a local variable out of the function.
其中最重要的是从函数中返回局部变量的地址。 De-referencing that pointer invokes undefined behaviour and no good can come of that.
取消引用该指针会调用未定义的行为,并且不会有任何好处。 A dynamic allocation is needed as things stand.
事情就是需要动态分配。
Your parameters should be const char* rather than char*. 您的参数应该是const char *而不是char *。 Using the latter makes it inconvenient to pass constand strings to your function.
使用后者使得将const和字符串传递给函数变得不方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.