基于char实现可扩容二维动态数组 修正动态分配引发的字符串拼接异常
基于char类型的动态二维字符串数组问题修正
现存核心缺陷
- 外层指针数组未实现动态扩容:
add函数仅在数组长度为1时分配初始的char*数组,后续新增元素时没有重新申请更大的内存块、迁移原有指针,直接对越界下标(如data[1])写入,导致内存覆盖、字符串拼接异常。 display函数缺少循环体大括号:cout << endl;被排除在逐行输出的循环范围外,所有字符串会拼接完成后才输出一次换行,无法实现每行存储一个字符串的效果。- 越界写入操作:
add函数中data[length - 1][strlen(word) + 1] = '\0';属于越界访问:new char[strlen(word)+1]的合法下标范围是0 ~ strlen(word),且strcpy_s已自动在字符串末尾写入终止符,该行操作多余且会破坏相邻内存块。
修正后的实现代码
#include <iostream> #include <cstring> using namespace std; void display(char** data, int length) { for (int i = 0; i < length; i++) { for (int j = 0; data[i][j] != '\0'; j++) { cout << data[i][j]; } cout << endl; } } void add(char** &data, int length, char* word) { // 扩容外层指针数组 char** new_data = new char*[length]; // 迁移原有指针 for (int i = 0; i < length - 1; i++) { new_data[i] = data[i]; } // 释放旧的外层指针数组 delete[] data; data = new_data; // 分配当前字符串的内存空间 int word_len = strlen(word); data[length - 1] = new char[word_len + 1]; strcpy_s(data[length - 1], word_len + 1, word); } int main() { char** data = NULL; int choice = 0, length = 0; char name[80]; cout << "Enter your choice" << endl; while (cin >> choice && choice != 3) { switch (choice) { case 0: cout << "Enter name to add: " << endl; cin.ignore(); cin.getline(name, 80); length++; add(data, length, name); display(data, length); break; } cout << endl << "Enter your next choice: " << endl; } // 释放所有动态申请的内存 for (int i = 0; i < length; i++) { delete[] data[i]; } delete[] data; return 0; }
修正效果
新增字符串后会逐行独立输出,不会出现jhonmarc这类拼接的异常情况。
内容的提问来源于stack exchange,提问作者codingbest
相关产品推荐
相关产品推荐

