Thread: Difference??

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Oct 2013
    Location
    Somewhere on this planet
    Posts
    3

    Difference??

    What is the main difference between the two declarations given below:

    1. pi=(int*)malloc(sizeof(int));

    2. pi=malloc(sizeof(int));

    As far as I've learned, in the 1st declaration, the first byte of the memory of size of integer is returned to pi, which is of integer type. But then, what's the second declaration for?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Assuming that pi is an int* or what amounts to an int*, and that the <stdlib.h> header was included, there is no difference.

    #1 merely does a type cast whereas #2 relies on the implicit conversion from void* to whatever the type of pi is. #2 has an advantage in that if you forget to #include <stdlib.h>, the compiler will likely warn you about a type conversion problem, whereas the type cast with #1 will likely silence such a warning. On the other hand, if you were writing code that is also intended to be compilable as C++, #1 is necessary since C++ does not provide an implicit conversion from void*.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Oct 2013
    Location
    Somewhere on this planet
    Posts
    3
    Thanks a lot

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. HD difference?
    By yaya in forum Tech Board
    Replies: 28
    Last Post: 09-05-2009, 06:03 PM
  2. Difference Between C And C++
    By nathanpc in forum C++ Programming
    Replies: 13
    Last Post: 07-16-2009, 01:57 PM
  3. difference between ++ and +=1
    By karthigayan in forum C Programming
    Replies: 18
    Last Post: 07-10-2009, 07:42 AM
  4. The difference?
    By Machewy in forum C++ Programming
    Replies: 3
    Last Post: 04-29-2003, 03:31 PM
  5. difference?
    By newbie_grg in forum C# Programming
    Replies: 9
    Last Post: 09-13-2002, 11:57 AM

Tags for this Thread