Monday, 9 January 2017

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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...