Thread: How to allocate memory using void*?

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    15

    How to allocate memory using void*?

    This is how I allocate in main:
    Code:
    Ax r = (Ax)malloc(nr*sizeof(Tx));
    And in function:
    Code:
    void* r = (void*)malloc(nr*d)
    Ax is a pointer to a struct;
    d = sizeof(Tx);

    The function will return the "r" for which it is supposed to allocate memory.

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    The only bugaboo in that is allocating void* gives you a "typeless" blob of memory and from there you have to use a typecast every time you access it.

    There is no penalty in allocating typed memory... all you're really doing is telling the compiler what to expect in that location so that you don't have to typecast.

  3. #3
    Registered User
    Join Date
    Nov 2010
    Posts
    15
    I need that function to work for any type. I should have mentioned that in the OP.

    Is the allocation correct?

  4. #4
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    yes, you don't need to case malloc() return value. because it's already returning void * type.
    just make sure that memory allocated is enough for your type.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. I'm donating my vector lib.
    By User Name: in forum C Programming
    Replies: 23
    Last Post: 06-24-2010, 06:10 PM
  2. Where does compiler allocate memory for Char x[] = "abc" ?
    By meili100 in forum C++ Programming
    Replies: 13
    Last Post: 10-20-2009, 05:02 AM
  3. Assignment Operator, Memory and Scope
    By SevenThunders in forum C++ Programming
    Replies: 47
    Last Post: 03-31-2008, 06:22 AM
  4. Allocate a big dynamic memory location
    By vnrabbit in forum C Programming
    Replies: 11
    Last Post: 10-09-2002, 08:02 AM
  5. Manipulating the Windows Clipboard
    By Johno in forum Windows Programming
    Replies: 2
    Last Post: 10-01-2002, 09:37 AM