【发布时间】:2015-03-26 21:03:01
【问题描述】:
我有一个名为 record 的结构,其中包含键值对:
struct Record{
char* key=new char();
TYPE value=NULL;
Record(){
key = "default";
value = 10;
}
Record(const char* key_, TYPE value_){
strcpy(key, key_);
value = value_;
}
const Record<TYPE>& operator=(const Record<TYPE>& other){
key = other.key;
value = other.value;
return *this;
}
};
另外,我有一个类“SimpleTable”,其中包含这些记录的数组:
class SimpleTable:public Table<TYPE>{
struct Record<TYPE> *table;
public:
当我尝试将日期放入这些记录时,问题就来了。我的 strcpy 给了我“访问冲突写入位置”。 (在类构造函数中初始化的 Records 数组的所有元素):
template <class TYPE>
bool SimpleTable<TYPE>::update(const char* key, const TYPE& value){
for (int i = 0; i < 10; i++){
if (table[i].key == ""){
strcpy(table[i].key , key); // <-------- crash right here
table[i].value = value;
}
}
return true;
}
【问题讨论】:
-
char* key=new char();分配一个字符。char* key=new char[10];在那里根据需要分配一个数组。赋值运算符中的key = other.key;也是错误的。 -
您分配了一个字符,然后继续在其上复制整个字符串,您期望什么?
-
请不要大写实际上是小写的 C 标识符(在我编辑之前,您的标题有
Strcpy而不是strcpy)。很容易有另一个函数叫做Strcpy。
标签: c++ arrays string struct strcpy