Initializing array of integer pointer in C

前端 未结 3 1885
无人及你
无人及你 2020-12-16 01:13

I have some confusions/problems about the usage of pointers in C. I\'ve put the example code below to understand it easily. Please notice differences of these codes. If you

3条回答
  •  攒了一身酷
    2020-12-16 02:02

    The comma-separated list of values is a construct for initializing arrays. It's not suitable for initializing pointers to arrays. That's why you need that (int[]) - it tells gcc to create an unnamed array of integers that is initialized with the provided values.

    gcc won't let you losing the information that arr is an array unless you really want to. That's why you need a cast. It's better that you declare arr as an array, not as a pointer. You can still pass it to the functions that accept a pointer. Yet gcc would not let you leak memory with malloc:

    error: incompatible types when assigning to type ‘int[5]’ from type ‘void *’
    

    If you want a variable that can be either an array or an pointer to allocated memory, create another variable for that. Better yet, create a function that accepts a pointer and pass it either an array or a pointer.

提交回复
热议问题