首先,确保在使用cstring之前已经正确初始化。其次,可以尝试使用std::string代替cstring,以避免出现问题。如果必须使用cstring,则需要确定你正确地复制了数据。另外,您应该考虑使用内存分配函数来分配并释放内存,例如memcpy和malloc。以下是一个示例代码,演示了几个实用技巧。
#include <cstring>
#include <iostream>
struct Node {
char data[20];
Node* next;
};
void copy_data(char* dest, const char* src, const size_t size) {
// 将src所指向的数组复制到dest所指向的数组中
std::memcpy(dest, src, size);
}
int main() {
Node* head = nullptr;
// 插入新节点
Node* new_node = new Node;
copy_data(new_node->data, "Hello, World!", sizeof("Hello, World!"));
new_node->next = head;
head = new_node;
// 遍历节点
for (Node* ptr = head; ptr != nullptr; ptr = ptr->next) {
std::cout << ptr->data << std::endl;
}
// 释放内存
while (head != nullptr) {
Node* temp = head;
head = head->next;
delete temp;
}
return 0;
}