我在函数内创建一个动态数组。代码(在下面发布)运行没有问题。我想知道我写的方式是正确的方式还是将来会在更复杂的代码中产生问题。我知道我的程序(以下)试图实现的特定任务可以通过字符串或向量更好地实现。但是我创建了这个人为的例子来解决我的问题。但是,如果您强烈希望避免使用动态数组,请随时分享您的观点和理由。

我先前研究的结果:我找不到关于使用new []创建动态数组并随后在不同范围内删除它们的合法性和道德性的连贯讨论。

感谢您的想法和见解。

我的示例代码如下:

=========================

#include<iostream>
#include<string>
#include<cctype>
using namespace std;

void getNonPunct(string _str, char* &_npcarr, int &_npsize);

int main()
{
    string input_string;
    char* npchar_arr;
    int npsize;

    cout << "Enter any string: ";
    getline(cin, input_string);

    getNonPunct(input_string, npchar_arr, npsize);

    // Now display non-punctuation characters in the string
    cout << "string with non-punctuation characters removed:\n";

    for (int n = 0; n <= npsize - 1; n++)
        cout << npchar_arr[n];
    cout << "\n(" << npsize << ") non-punctuation characters\n";

    // Now return the memory allocated with 'new' to heap

    delete [] npchar_arr;
    // Is it okay to 'delete' npchar_arr eve if it was created in the function
    // getNonPunct() ?

    return(0);
}
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void getNonPunct(string _str, char* &_npcarr, int &_npsize)
//This void function takes an input array of strings containing arbitrary
//characters and returns a pointer to an array of characters containing only
//the non-punctuation characters in the input string. The number of
//non-punctuation characters are stored in size. Prior to the function call,
//int_arr and size are undefined. After the function call, char_arr points to
//the first location of an array of the non-punctuation character array.
//'size' is equal to the number of non-punctuation characters in the input
//string.
{

    // First get the number of non-punctuation characters in the string

    int str_len, npcount = 0;

    str_len = static_cast<int>( _str.length() );

    _npsize = 0;
    for (int i = 0; i <= str_len - 1; i++)
    {
        if ( !ispunct(_str[i]) )
            _npsize++;
    }

    // Now that you know how many non-punctuation characters are in the string,
    // create a (dynamic) character array of _npsize.

    _npcarr = new char [_npsize];


    for (int k = 0; k <= str_len - 1; k++)
    {
        if ( !ispunct(_str[k]) )
            _npcarr[npcount++] = _str[k];
    }

    return;
}

最佳答案

有效吗是。 npchar_arr指向的数组一直存在,直到您销毁它为止,并且可以在另一个函数中使用delete[]表达式销毁它。

这是个好主意吗?不会。使用自动管理对象寿命的智能指针会更好,这使您摆脱了手动手动设置指针的职责。

如果编译器和标准库支持delete[],或者如果不能使用std::unique_ptr<char[]>(在Boost和C ++ TR1中也可以找到unique_ptr),请考虑使用std::auto_ptr

07-24 18:13