-2

Everyones suggesting not to cast while allocating a pointer here, do I cast result of malloc

But my below non-casted code produce compiler error in VS-2013. Why!

#include <stdio.h>
#include <malloc.h>

int main(){
    int *ptr = malloc(sizeof(int) * 100);  // compiler error
    return 0;
}

Compiler error is,

1 IntelliSense: a value of type "void *" cannot be used to initialize an entity of type "int *"

Sazzad Hissain Khan
  • 37,929
  • 33
  • 189
  • 256
  • 6
    Considering that you posted with the C++ tag: what is unclear to you? C++ isn't C. In this case the implicit conversion from `void*` to `T*` which is supported in C is not supported in C++. – Dietmar Kühl Nov 09 '17 at 04:31
  • 2
    Don't use `malloc` and friends in C++. If you need a runtime changeable container use [`std::vector`](http://en.cppreference.com/w/cpp/container/vector). If the size is fixed at compile-time use [`std::array`](http://en.cppreference.com/w/cpp/container/array). If you are required to use pointers, use *smart pointers* (like [`std::unique_ptr`](http://en.cppreference.com/w/cpp/memory/unique_ptr)). And if you are forced to use raw non-owning pointers, use `new` or `new[]` instead. – Some programmer dude Nov 09 '17 at 04:32
  • 1
    If this is related to your [previous question](https://stackoverflow.com/questions/47193732/how-to-free-dynamic-array-of-structure-in-c), that one was tagged with C. This is C++. C and C++ are two different languages, with different behavior and semantics. – Some programmer dude Nov 09 '17 at 04:36
  • Thanks @Someprogrammerdude. Its clear now. – Sazzad Hissain Khan Nov 09 '17 at 04:39
  • 2
    In C++ you should not use `malloc` – M.M Nov 09 '17 at 04:52
  • @Someprogrammerdude Errm if you use `new` with a raw pointer is it not then *by definition* an *owning* pointer? – Galik Nov 09 '17 at 05:35
  • @Galik The smart pointers have ownership semantics. Raw pointers do not. – Some programmer dude Nov 09 '17 at 05:38
  • 2
    @Someprogrammerdude The way I understand it is *ownership* refers to the pointer that is responsible for the destruction of the object it points to. So raw pointers can be *owners* but because you have to delete the objects they own manually they are unreliable. So the rule is to avoid *owning* raw pointers. An example of non-owning raw pointers would be an iterator pointing to an element that is owned by something else (a container, smart pointer or (hopefully not) another raw pointer). – Galik Nov 09 '17 at 05:44

1 Answers1

4

The advice in the other question is strictly for C only.

In C++, you need the cast, since C++ does not allow implicit conversion of a void* pointer to any other pointer type.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34