3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

c言語での文字列ポインタと文字列配列の違い

Posted at

C言語での文字列操作の違いをまとめてみました。

宣言 変数入れ替え 文字列操作
char[] コンパイルエラー OK
char* OK ランタイムエラー
const char* OK コンパイルエラー
char* const コンパイルエラー ランタイムエラー
const char* const コンパイルエラー コンパイルエラー

文字列配列は宣言したときにchar[]という型で宣言されるのでそれ以降ポインタ型の文字列は受け付けないのでコンパイルエラーが出ると思われる。
文字列ポインタは変数そのものの中身は入れ替えることはできるが変数が指している文字列自体の変更はできないと思われる。読み取り専用のメモリに置かれるのでセグメンテーションフォールトが発生する。

テスト用のプログラムを作ったので置いておきます。

# include <stdio.h>
 
int main() {
        char chararray[] = "chararray";
        char chararray2[] = {'c', 'h', 'a', 'r'};
        //chararray = chararray2;                   // compile error - incompatible types when assigning to type 'char[10]' from type 'char *' 
        //chararray = "chararray_change";           // compile error - incompatible types when assigning to type 'char[10]' from type 'char *'
        chararray[0] = '0';
        printf("%s\n", chararray);
 
        char* charp = "charp";
        charp = "charp_change";                     // OK
        //charp[0] = '0';                           // runtime error - segmentation fault
        printf("%s\n", charp);
 
        const char* constchar = "constchar";
        constchar = "constchar_change";             // OK
        //constchar[0] = '0';                       // compile error - read only variable
        printf("%s\n", constchar);              
 
        char* const charconst = "charconst";
        //charconst = "charconst_change";           // compile error - read only variable
        //charconst[0] = '0';                       // runtime error - segmentation fault
        printf("%s\n", charconst);
 
        const char* const constcharconst = "constcharconst";
        //constcharconst = "constcharconst_change"; // compile error - read only variable
        //constcharconst[0] = '0';                  // compile error - read only variable
        printf("%s\n", constcharconst);
}
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?