0

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?

ChrisMcJava
  • 1,965
  • 4
  • 24
  • 33

2 Answers2

3

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.

Community
  • 1
  • 1
Mitch Wheat
  • 288,400
  • 42
  • 452
  • 532
0

malloc()'s return type is a void *

So when it gets assigned it needs to get converted to an int*

Doing (int*) does this explicitly. If that's not done, it is done implicitly by the compiler.

A pointer is a pointer, it's only the compiler trying to give you type safety that has any bearing at all. With some compilers with certain flags you'll get a warning if the explicit (int*) cast isn't there. The actual resulting compiled code is exactly the same in both cases.

So as Mitch said, it does absolutely nothing.

Brad Peabody
  • 9,954
  • 8
  • 39
  • 60
  • The result needs to be *converted*, not cast, to `int*`. A "cast" is an explicit operator, consisting of a type name in parentheses. `int *ptr = malloc(...);` converts the `void*` result to `int*` without a cast, an implicit conversion. – Keith Thompson Sep 22 '13 at 01:10
  • @KeithThompson Good point, answer edited. – Brad Peabody Sep 22 '13 at 01:19