1

In C address returned by malloc() typecasts implicitly and in C++ I need to typecast explicitly. But I'm using an integer pointer which will point out to next address according to the pointer arithmetic, then why do I need to typecast memory address?

I'm actually using 'new' keyword but I need to clear my thought on this.

  • 1
    C and C++ are two *very* different languages. Unless you want to take a class learning C++, then I suggest [a couple of the books listed here](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282). – Some programmer dude Nov 06 '18 at 13:21
  • 3
    Don't use malloc in C++. (there is low level stuff where you may need to but stick with `new` until then (and then don't even use `new` and use RAII containers like `vector` and smart pointers)) – NathanOliver Nov 06 '18 at 13:22
  • 1
    You don't need to typecast for either. And for C++ if you're using `new` properly (which, in modern C++ means you're not using it regardless), it normally shouldn't require type-casting. Your question would be well-served to include a realistic example where you feel typecasting is required in your C++. Odds are, neither casting nor dynamic manual management is needed at all. – WhozCraig Nov 06 '18 at 13:24
  • 3
    can you show an example where you think you need a cast? – 463035818_is_not_an_ai Nov 06 '18 at 13:25
  • dynamically allocating memory is as simple as `std::vector x;`, no need for `new` or casting ;) – 463035818_is_not_an_ai Nov 06 '18 at 13:25
  • @user463035818 Something like this I presume? http://coliru.stacked-crooked.com/a/47ce070800ee19cf – HolyBlackCat Nov 06 '18 at 13:28
  • [link] (http://https://ideone.com/0hRWv9) –  Nov 06 '18 at 13:29
  • @HolyBlackCat didnt say that I cannot imagine a situation where you would need a cast, but wanted to know what the question is about – 463035818_is_not_an_ai Nov 06 '18 at 13:29
  • And please read [Do I cast the result of malloc?](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) (and note that it's for C only). – Some programmer dude Nov 06 '18 at 13:30
  • don't use malloc. Don't use `new`. Don't use manual memory management. Use containers and smart pointers. – bolov Nov 06 '18 at 13:33
  • *"Don't use `new`."* Except when writing a custom container, which for some reason can't be implemented properly using standard containers and smart pointers. Even then you should be very careful. – HolyBlackCat Nov 06 '18 at 13:36

1 Answers1

9

But I'm using an integer pointer which will point out to next address according to the pointer arithmetic

Yes it will, but it's not revelant here.

malloc returns a void *.

In C, a pointer to void can be implicitly converted to a pointer to any other type.

In C++, there is no such implicit conversion (presumably to make the language a bit more safe to use).

It's as simple as that.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207