-4

次のようなサイズの文字ポインタの配列を 1 つ作成するとします。

 char* temp[10];
//need intialisation here..
temp[0] = "BLAH";
temp[1] = "BLAH";
temp[3] = "BLAH";
.
.
.
temp[9] = "BLAH";    
//Need reinitialise..
temp[10] = "BLAH";
temp[11] = "BLAH";
  1. どうすれば初期化できますか?

  2. しばらくしてからサイズ 20 で再初期化する方法は?

  3. malloc()これを行うのにcalloc()便利ですか?はいの場合、文字へのポインタの配列で使用する方法は?

[編集]

私のコードと要件、基本的にはCでファイルを読み取りたいが、1文字を無駄にすることはありません...テキストファイルからデータを読み取るコードは次のとおりです。

FILE *ptr_file;
/* Allocate space for ten strings */
/* Allocate space for ten strings */
char** list  = (char **)malloc(10 * sizeof(char));

/* Reallocate so there's now space for 20 strings */                    

/* And initialize the new entries */

ptr_file =fopen(LogFileCharName,"rb");
if (!ptr_file)
    return 1;
int __index = 0;
wchar_t CurrentString[1000];
while(fgetws (CurrentString , 1000 , ptr_file) != NULL)
{
    char* errorDes;
    errorDes = new char[1000];
    wcstombs(errorDes, CurrentString, 1000);
    list[__index] = errorDes;
    if( __index>10)
      {
             (char**)realloc(list, 20 * sizeof(char *));
     }
    __index++;
}

サイズが10を超えた場合、サイズを変更する必要があります。このために、Microsoft Visual Studio の win32 コンソール アプリケーション タイプを使用しています。

4

1 に答える 1

2

配列は使用しませんが、ポインターを使用してヒープに割り当て、必要に応じて再割り当てします。

/* Allocate space for ten strings */
char **temp = malloc(10 * sizeof(char *));

temp[0] = "Hello 1";
/* ... */
temp[9] = "Hello 10";

/* Reallocate so there's now space for 20 strings */
temp = realloc(temp, 20 * sizeof(char *));

/* And initialize the new entries */
temp[10] = "Hello 11";

初期化に関しては、文字列の内容によって異なります。既存の文字列 (上記の例のような文字列リテラル、または他の文字列) を指すようにするか、ヒープ上の文字列にもスペースを割り当てます。

多分このようなもの:

for (int i = 0; i < 10; i++)
{
    char temp_string[10];

    /* Create strings in the form "Hello 1" to "Hello 10" */
    sprintf(temp_string, "Hello %d", i + 1);

    /* Duplicate the temporary string */
    temp[i] = strdup(temp_string);
}

注: egstrdupまたはmalloc/callocを使用して実際の文字列を割り当てる場合は、もちろんfreeそれらも使用する必要があります。


更新された質問の後、コードにいくつかの問題があります。

  • 1つ目は、チェック__index>10を行うと、すでに2つのインデックスが配列の範囲外になっていることです。チェックは です__index==9
  • 上記の変更を行うと、インデックスが11以上になると継続的に再割り当てするという他の問題も解決します。
  • 配列内の実際の文字列に使用するため、実際の文字列を解放するときnewに使用する必要があります。delete
  • を使用newしているため、C++ を使用しています。C++ には、次のような処理を行うためのはるかに優れた機能があります。

    // Declare and open file
    wifstream ifs(LogFileCharName);
    
    std::vector<std::string> list;
    
    std::wstring CurrentString;
    
    while (std::getline(ifs, CurrentString))
    {
        // Get the needed length of the destination string
        size_t length = wcstombs(nullptr, CurrentString.c_str(), 0);
        char* tmp = new char[length + 1];
    
        // Do the actual conversion
        wcstombs(tmp, CurrentString.c_str(), length + 1);
    
        // Add to list
        list.emplace_back(tmp);
    
        delete [] tmp;
    }
    
于 2013-05-08T06:05:52.923 に答える