現時点では、変数 d にメモリが割り当てられていません。
正しくない。これ:
char d[6];
は初期化されていない 6 の配列でありchar
、スタック上のメモリが割り当てられています。free()
スタック変数は、初期化されているかどうかにかかわらず、明示的に dする必要はありません。スタック変数が使用するメモリは、スコープ外になると解放されます。または経由malloc()
で取得したポインタのみを に渡す必要があります。realloc()
calloc()
free()
初期化するには:
char d[6] = "aaaaa"; /* 5 'a's and one null terminator. */
また:
char d[] = "aaaaa"; /* The size of the array is inferred. */
そして、すでにmathematician1975が指摘しているように、配列の割り当ては違法です。
char d[] = "aaaaa"; /* OK, initialisation. */
d = "aaaaa"; /* !OK, assignment. */
strcpy()
, strncpy()
, memcpy()
,snprintf()
などを使用してd
、宣言後にコピーしたり、 のchar
個々の要素に を代入したりできますd
。
char[] が初期化されたことを知る方法は? Filled(d){..} の場合はパターンが必要です
配列がヌルで終了している場合は、使用できますstrcmp()
if (0 == strcmp("aaaaaa", d))
{
/* Filled with 'a's. */
}
またはmemcmp()
、null で終了していない場合に使用します。
if (0 == memcmp("aaaaaa", d, 6))
{
/* Filled with 'a's. */
}
char[] を 1 種類の文字で埋める方法は?
使用memset()
:
memset(d, 'a', sizeof(d)); /* WARNING: no null terminator. */
また:
char d[] = { 'a', 'a', 'a', 'a', 'a', 'a' }; /* Again, no null. */