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
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.
When you say: ptr = {1,2,3,4,5}
, you make ptr
point to a memory in the data segment, where constant array {1,2,3,4,5}
resides and thus you are leaking memory. If you want to initialize your memory, just after allocation, write: ptr[0]=1; ptr[1]=2;
and so on. If you want to copy data, use memcpy.
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.