What is the difference between char s[] and char *s?Cでエラーが返される理由
私は与えられたリンクに基づいて2つのコードの例を挙げました。 getstring()関数を仮定します。両方として
char *str = "GfG"; /* "GfG" is stored in read only part of shared segment */
/* str has auto storage duration,so stored on the stack
/* No problem: remains at address str after getString() returns*/
return str;
AND
char str[] = "GfG"; /* "GfG" is stored in read only part of shared segment */
/* str has auto storage duration,so stored on the stack.
/* Problem: string may not be present after getSting() returns */
return str;
自動保管期間及びスタック・セグメントに格納された両方の変数を有しています。
次に、なぜ最初の1のためではなく秒1のために働く戻りSTR?
最初はstatic lifetimeの文字列リテラルへのポインタを返します。これは 'getString()'のスコープが残っていると破壊されません。しかし、第二に、 '' GfG ''は実際に文字列リテラルではなく、静的な生存期間を持たないので、生存期間は割り当てられた範囲に縛られます。このようにして、2番目に返されたポインタは無効となり、それを読み取ろうとすると未定義の動作が呼び出されます。 – George
'str []'を 'static char'と定義すると、関数を終了するときに破棄されません。 –
これを確認してくださいhttp://stackoverflow.com/questions/9970295/life-time-of-string-literal-in-c – Karthick