Tuesday, October 1, 2019

pointers - when allocating memory for an array dynamically (in C), what does the (int *) cast do?




C noob here. When declaring an array during runtime, I've seen two methods for doing so. Can someone please explain the (int *) cast in the second one?



// first way
int numberElements = 5;
int *pointer = malloc(numberElements * sizeof(int));

// second way
...
int *pointer = (int *)malloc(numberElements * sizeof(int));



I just don't see what the (int *) cast is doing. With first the allocation, the array can be filled like this...



// first way cont.
...
for (int i = 0; i < numberElements; i += 1){
pointer[i] = 0;\
}



is this not true for the second? what would you have to do differently?


Answer



The cast does nothing. A void pointer can be assigned to any pointer without an explicit cast.



AND you shouldn't. The C99 (or C90, C11) standard does not require the cast.


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...