Why character pointer is getting assigned just a character, while a string is supposed to get assigned to it?

后端 未结 1 1427
感情败类
感情败类 2021-01-28 18:38

A string contains three parts separated by space. First two parts are strings and the third part is an integer.

The output of the below program is surprising me.

相关标签:
1条回答
  • 2021-01-28 18:45

    This line is wrong:

    arr=malloc(N*sizeof **arr);
    

    it should be:

    arr=malloc(N*sizeof *arr);
    

    **arr is a char, so it's only allocating space for N bytes, but you need space for N pointers, which are 4 bytes. So you're not allocating enough space, and then you're writing outside the array bounds, resulting in undefined behavior.

    DEMO

    0 讨论(0)
提交回复
热议问题