字符指针出现C++错误
C++ error on char pointer
我想初始化结构中的char*字符串。
这是结构:
typedef struct __String {
char* data; // C-string data,
unsigned* copyRef; // number of copy reference, delete only when the copyRef is 0
bool isACopy; // this boolean is true when *data is a ref to an other MyString
__String () {
data = 0;
isACopy = false;
copyRef = new unsigned();
*copyRef = 0;
return;
}
void addCopyRef() {
*copyRef++;
}
void removeCopyRef() {
*copyRef--;
}
} *MyString;
这就是它的特点。。
void Initialize(MyString& string){
string->data = new char[LENGHT];
string->data[0] =' '; // this generate an error!
string->addCopyRef();
}
这是主要的:
MyString left_string, right_string, both_string;
Initialize(left_string);
Initialize(right_string);
Initialize(both_string);
第一个进展顺利,第二个进展不顺利。。你能帮我弄清楚问题出在哪里吗?谢谢
在像这样传递对象之前,您需要为对象分配内存:
MyString left_string = new __String();
Initialize(left_string);
一般建议不要做这样的typedef,它们非常令人困惑,而且容易出错。如果您决定对指针进行typedef,则至少表明它是类型中的指针,即:typedef struct __String* MyStringPtr
。
typedef struct __String {
char* data; // C-string data,
unsigned* copyRef; // number of copy reference,
// delete only when the copyRef is 0
bool isACopy; // this boolean is true when *data
// is a ref to an other MyString
__String () {
data = 0;
isACopy = false;
copyRef = new unsigned;
*copyRef = 0;
return;
}
void addCopyRef() {
*copyRef++;
}
void removeCopyRef() {
*copyRef--;
}
} *MyString;
void Initialize(MyString& string){
string->data = new char[100];
string->data[0] =' '; // this generate an error!
string->copyRef = new unsigned();
string->addCopyRef();
}
int main()
{
MyString mystring = new struct __String;
Initialize(mystring);
}
我这样测试没有任何错误。在linux上使用g++。我想你最好
- 至少在此处提供错误消息
- 以及您所使用的编译器和平台
我用下面的另一个main((再次进行了测试。
int main()
{
MyString mystring = new struct __String;
MyString mystring1 = new struct __String;
MyString mystring2 = new struct __String;
Initialize(mystring);
Initialize(mystring1);
Initialize(mystring2);
}
使用此测试代码,不会出现错误。我认为您错过了实例化由mystring
(在您的代码中,left_string
、right_string
、both_string
(指向的对象。我想这就是为什么。
这段代码会从构造函数中产生内存泄漏。在这种代码状态下,不需要构造函数。
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 错误:未在此范围内声明'reverse'