8

簡単なサンプルプログラムはこちら

#include <stdio.h>
#include <string.h>

const char *hello_string = "Hello";

int main(void)
{
char *world_string = " World";
static char hello_world[strlen(hello_string)+strlen(world_string)];
strcpy(&hello_world[0], hello_string);
strcat(&hello_world[0], world_string);
printf("%s\n", hello_world);
return 0;
}

コンパイラ出力:

test.c: In function ‘main’:
test.c:9:13: error: storage size of ‘hello_world’ isn’t constant
static char hello_world[strlen(hello_string)+strlen(world_string)];
            ^

この場合、「静的」を完全に無用で不必要に使用するとエラーが発生し、それを削除すると問題なくコンパイルされることを認識しています。これは、私の質問を説明するための簡単な例です。

私が理解していないのは、「hello_string」がconst char * として宣言され、そのサイズが実行中に変更されない場合に、ストレージ サイズが一定ではない理由です。これは、コンパイラがそれを知るほど賢くないという単なるケースですか?

4

4 に答える 4

5

ストレージ サイズが一定でないことについてコンパイラが不平を言う場合、それは暗黙のうちにcompile-time constant、つまりコンパイラがコンパイル時に決定できる値を意味します。の呼び出しはstrlen明らかに実行時に行われるため、コンパイラは配列のサイズを知ることができません。

これを試して:

#include <stdio.h>
#include <string.h>

const char hello_string[] = "Hello";

int main(void)
{
    char world_string[] = " World";
    static char hello_world[sizeof hello_string + sizeof world_string];
    strcpy(&hello_world[0], hello_string);
    strcat(&hello_world[0], world_string);
    printf("%s\n", hello_world);
    return 0;
}
于 2013-09-01T21:18:57.193 に答える
4

strlen関数です。戻り値はコンパイル時に計算できません。

于 2013-09-01T21:08:20.880 に答える
2

static配列宣言でストレージ クラスの指定を使用しました。

static配列は固定長のみを持つことができます。つまり、配列のサイズは整数定数式でなければなりません。関数呼び出しを伴う式は定数式ではありません。

static可変長配列を使用する場合は、指定子を削除してください。そして、null ターミネータ用に配列に余分な文字を予約することを忘れないでください。

于 2013-09-01T21:18:32.127 に答える
0

strlen()関数呼び出しです。コンパイラは、それが何をするかを知りません。

試してみてくださいsizeof (*hello_string)。それがうまくいくかどうかはわかりません。

またはconst char hello_string[] = "Hello"sizeof(hello_string)私にはうまくいく可能性が高いようです。

于 2013-09-01T21:09:42.857 に答える