Initializing array of integer pointer in C

前端 未结 3 1912
无人及你
无人及你 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 01:39

    The malloc calls in the first few examples allocate a block of memory and assign a pointer to that memory to arr. As soon as you assign to arr again, the pointer value is overwritten, and you've lost track of that allocated memory -- i.e., you've leaked it. That's a bug right there.

    In other words, if you allocate a block of memory using using malloc(), then you can write data into it using array syntax (for example):

    int* arr = (int *) malloc(sizeof(int) * 5);
    for (int i=0; i<5; ++i)
        arr[i] = i;
    

    But you can't assign anything else directly to arr, or you lose the pointer to that block of memory. And when you allocate a block using malloc(), don't forget to delete it using free() when you don't need it anymore.

    An array is not a pointer-to-integer; it's an array. An array name is said to "decay to a pointer" when you pass it as an argument to a function accepting a pointer as an argument, but they're not the same thing.

    Regarding your last question: that's actually the difference between an array and a pointer-to-type: the compiler knows the size of an array, but it does not know the size of a block pointed to by an arbitrary pointer-to-type. The answer, unfortunately, is no.

    But since you're writing C++, not C, you shouldn't use arrays anyway: use `std::vector'! They know their own length, plus they're expandable.

提交回复
热议问题