关于 char* xxx[] 的使用,该如何处理
关于 char* xxx[] 的使用
问题一:这个程序编译时无错,运行时 newstring_a[0] 却为“This is a long text line!”,不知为何。
问题二:程序末尾注释掉了 DestroyCopy,取消注释重新编译无错,但是运行时程序会在 delete[] 处崩溃,不知为何。
望达人解答,谢谢!
------解决方案--------------------
如:
char* s[10];
s[0]="aaa";
s[1]="bbb";
应该是可用的
------解决方案--------------------
new char(10) // 分配一个char,并把它的初值赋为 10
new char[10] // 分配10个char,没有初值
------解决方案--------------------
最微妙的距离:[]与()
------解决方案--------------------
------解决方案--------------------
呵呵,细心一点好!
- C/C++ code
#include <cstring> #include <iostream> using namespace std; int ConstStringCopy(char* NewStringList[], const char* ConstStringList[], const int& lines) { int i = 0; for (; i<lines; ++i) { NewStringList[i] = NULL; NewStringList[i] = new char(strlen(ConstStringList[i]) + 1); strncpy(NewStringList[i], ConstStringList[i], strlen(ConstStringList[i])+1); } return i; } void DestroyCopy(char* NewStringList[], const int& lines) { int i = 0; while ((NULL!=NewStringList[i]) && (i<lines)) { delete[] NewStringList[i]; NewStringList[i] = NULL; ++i; } } int main () { const char* string_a[1] = {"This is a long text line. This is a const string convertion utility."}; const char* string_b[2] = {"AAA", "BBB"}; char* newstring_a[1]; char* newstring_b[2]; ConstStringCopy(newstring_a, string_a, 1); ConstStringCopy(newstring_b, string_b, 2); cout << newstring_a[0] << endl; cout << newstring_b[0] << endl; cout << newstring_b[1] << endl; // DestroyCopy(newstring_a, 1); // DestroyCopy(newstring_b, 2); return 0; }
问题一:这个程序编译时无错,运行时 newstring_a[0] 却为“This is a long text line!”,不知为何。
问题二:程序末尾注释掉了 DestroyCopy,取消注释重新编译无错,但是运行时程序会在 delete[] 处崩溃,不知为何。
望达人解答,谢谢!
------解决方案--------------------
如:
char* s[10];
s[0]="aaa";
s[1]="bbb";
应该是可用的
------解决方案--------------------
new char(10) // 分配一个char,并把它的初值赋为 10
new char[10] // 分配10个char,没有初值
------解决方案--------------------
最微妙的距离:[]与()
------解决方案--------------------
------解决方案--------------------
呵呵,细心一点好!