Sunday, 8 October 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

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...