Thread: need help!

  1. #1
    Registered User
    Join Date
    Jan 2002
    Posts
    4

    need help!

    hi, im having trouble with this:

    "write a function that accepts two strings. Use malloc()
    function to allocate enough memory to hold the two strings after they have bgeen linked. return a pointer to this new string"

    when i try to allocate the memory:
    " pointer = malloc( 10 * sizeof(char)); "

    it say that i cannot "convert void types into char *"
    and how can i link the two strings toghether?

    thnks 4 ur help

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Type cast it, or use a C compiler instead of a C++ compiler. Additionally, make sure you're including the right header for malloc.

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    kiran
    Guest
    try this
    pointer = (char *)malloc(sizeof(char));
    l

  4. #4
    Registered User
    Join Date
    Feb 2002
    Posts
    2
    malloc() always returns a pointer to the object of void data type by default.In C compilers(especially turbo c)this warning shouldn't
    come but this is a problem with c++ compilers.
    Always type cast the return value of malloc() like

    CharPtr = (char*)malloc(10 * sizeof(char));

  5. #5
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,380
    >In C compilers(especially turbo c)this warning shouldn't
    >come but this is a problem with c++ compilers.

    I think you mean:

    In C compilers (especially turbo c) this warning DOESN'T come...

    Isn't it?

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,664
    > Always type cast the return value of malloc() like
    Never cast the result of malloc (not in any ANSI compiler at least)

    If you need to cast the result of malloc, and you're using C++, then you should be using the new operator anyway.

    If you need to cast the result of malloc, and you're using C, then it means you haven't included stdlib.h. The side effect of this is that C initially thinks that malloc returns an int (by the implicit declaration rules). On machines where ints and pointers are different sizes, this results in seriously incorrect code.

    On the off-chance that you're using some pre-ANSI fossil, then you still might need the cast.

    http://www.eskimo.com/~scs/C-faq/q7.7.html

  7. #7
    Registered User
    Join Date
    Jan 2002
    Posts
    4
    thanks for help guys

Popular pages Recent additions subscribe to a feed