char pointer initialization in C

前端 未结 6 1233
情书的邮戳
情书的邮戳 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-06 19:02

    There are several things to think about here. Your original example is below:

    char *ab = NULL;
     //ab = "abc123"; // works fine
     sprintf(ab, "abc%d", 123); // this line seems to crash the program
    

    char *ab = NULL; is a pointer to a character and is initialized to NULL;

    I don't think ab = "abc123"; worked fine unless it looked like char *ab = "abc123";. That is because you initialized char *ab to a read-only string. The initialization probably took place at compile time.

    Your sprintf(ab, "abc%d", 123); line failed, because you did not initialize any memory for the char *ab pointer ahead of time. In other words, you did not do something like:

    ab = malloc((sizeof(char) * 3) + 1); /* + 1 allows for null string terminator. */
    

    You can fix your problem one of two ways. Either allocate dynamic memory as shown above, or you can make the string an array of a fixed length, like char ab[25] = {0};. Usually, I create an array of a length like 1024, 256, or some number that will usually cover most of my string length cases. Then I use char pointers for functions that operate on the array.

提交回复
热议问题