char pointer initialization in C

前端 未结 6 1295
情书的邮戳
情书的邮戳 2021-02-06 18:30

I am not so clear on character pointer and how they work.

The program builds, but crashes when I run it.

 char *ab = NULL;
 //ab = \"abc123\"; // works f         


        
6条回答
  •  春和景丽
    2021-02-06 19:02

    Unlike in Java or other higher level languages, many of the C library's string functions don't simply set a string reference, instead they operate on a block of pre-allocated memory called a character array.

    Your first line is saying that ab points to a non-existent memory location.

    You'd have more luck if, instead of char *ab = NULL; you did either:

    char ab[12];
    

    or:

    char *ab = (char*)malloc(12);
    

提交回复
热议问题