简体   繁体   English

动态分配的字符串

[英]Dynamically allocated string

I have defined a struct that stores the length and content of a string. 我定义了一个存储字符串长度和内容的结构。

struct sir {
    int length;
    char* string;
};

I am trying to dynamically alocate memory space for this string using: 我正在尝试使用以下命令动态分配此字符串的内存空间:

s->string = malloc(sizeof(char) * (s->length));

But I keep getting this error: 但我不断收到此错误:

error C2440: '=' : cannot convert from 'void *' to 'char *' 

Can you please guide in finishing this function? 您能否指导完成此功能?

PS: I would really like to know how write values from keyboard in this newly created string? PS:我真的很想知道如何在这个新创建的字符串中从键盘写入值? Tnx in advance! 提前Tnx!

malloc() will return void * , which needs to be converted to char * explicitly in C++ (though not needed in C ). malloc()将返回void * ,它需要在C++显式转换为char * (尽管在C不需要)。

Try 尝试

s->string = (char *) malloc(sizeof(char) * (s->length));

Edit: As you're using C++ , as @chris commented, you should consider to use std::string instead. 编辑:当您使用C++ ,如@chris所评论的,您应该考虑使用std::string代替。 No manual memory management is needed. 无需手动内存管理。 If you must do it yourself, use new instead of malloc . 如果必须自己执行操作,请使用new而不是malloc

You are compiling the program as a C++ program. 您正在将该程序编译为C ++程序。 The return type of function malloc is void * However a pointer to void may not be implicitly converted to a pointer to other type in C++ and the error message says about this clear enough. 函数malloc的返回类型为void *但是,指向void的指针可能不会隐式转换为C ++中的其他类型的指针,并且错误消息对此也足够清楚。

So write 所以写

s->string = ( char * )malloc(sizeof(char) * (s->length));. 

However the coorect way is to use operator new instead of malloc in C++ 但是,正确的方法是在C ++中使用运算符new而不是malloc

s->string = new char[s->length];. 

Again if it is a C++ program then instead of the structure it would be better to use a class with explicitly defined constructors, destructor and the copy bassignment operator. 同样,如果它是C ++程序,则最好使用具有明确定义的构造函数,析构函数和复制重演算符的类,而不是结构。

Or compile your program as a C program if you indeed want to deal with a C program. 如果确实要处理C程序,则将其编译为C程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM