【发布时间】:2014-04-20 22:35:10
【问题描述】:
我已经定义了一个存储字符串长度和内容的结构体。
struct sir {
int length;
char* string;
};
我正在尝试使用以下方法为该字符串动态分配内存空间:
s->string = malloc(sizeof(char) * (s->length));
但我不断收到此错误:
error C2440: '=' : cannot convert from 'void *' to 'char *'
你能指导完成这个功能吗?
PS:我真的很想知道如何在这个新创建的字符串中从键盘写入值? 提前Tnx!
【问题讨论】:
-
将其替换为
std::string。无需手动内存管理。如果必须自己做,请使用new,而不是malloc。 -
c或c++?为什么在c++中使用malloc? -
另外请看这篇文章:do i cast the result of malloc?
-
我自己设法从键盘上写了值。所以别在意最后一个问题。谢谢大家的帮助!
标签: c++ string pointers malloc