首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于 char* xxx[] 的使用,该如何处理

2012-02-27 
关于 char* xxx[] 的使用C/C++ code#include cstring#include iostreamusing namespace stdint Const

关于 char* xxx[] 的使用

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,没有初值
[解决办法]
最微妙的距离:[]与()
[解决办法]
探讨
没有崩溃吗
char* newstring_a[1];
char* newstring_b[2];
并没用分配内存,NewStringList[i] = NULL;不会崩溃?

[解决办法]
呵呵,细心一点好!

热点排行