Tuesday 1 October 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...