Thread: Help with some syntax

  1. #1
    Registered User Alexis's Avatar
    Join Date
    Jan 2013

    Help with some syntax

    Hello, I have not been programming for very long at all, I've been working my way through a book, reading stuff online and making some simple programs. I recently learned about malloc and I understand how to use it and why it is useful but some of the syntax has left me confused. Here is a line from a malloc() example program:
    ptr_one = (int *)malloc(sizeof(int));
    What does (int *) do here, what does it mean? I have seen it used in several examples of malloc.
    Thank you

  2. #2
    Registered User
    Join Date
    Nov 2012
    In C++, this is a required syntax to tell the compiler that you want to convert the result from malloc, which is (void *) into (int *). In C, we normally write it like this

    int *ptr_one = malloc(sizeof(int));

    The compiler will automatically convert the right-hand side (void*) to the type of the left-hand side (int*). The type (int*) means pointer to int. The type (void*) basically means pointer to "something", where "something" is to be determined by the programmer.

    EDIT: you will also see the above line written this way

    int *ptr = malloc(n * sizeof(*ptr));
    This will allocate n items, each of the appropriate size (for example, int). This way if you later change the type, you need only change one word, example to allocate n doubles:

    double *ptr = malloc(n * sizeof(*ptr));
    Last edited by c99tutorial; 02-17-2013 at 05:38 PM.

  3. #3
    Registered User Alexis's Avatar
    Join Date
    Jan 2013
    Thank you so much, I really appreciate it!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Array Syntax Versus Pointer Syntax
    By LyTning94 in forum C++ Programming
    Replies: 6
    Last Post: 12-06-2011, 10:56 AM
  2. Help with syntax please.
    By chrismcc35 in forum C Programming
    Replies: 4
    Last Post: 03-04-2008, 07:18 PM
  3. syntax ?
    By bean66 in forum C Programming
    Replies: 3
    Last Post: 08-22-2007, 09:44 PM
  4. syntax help?
    By scoobygoo in forum C++ Programming
    Replies: 1
    Last Post: 08-07-2007, 10:38 AM
  5. About syntax and std::everything
    By Cobras2 in forum C++ Programming
    Replies: 13
    Last Post: 06-04-2003, 04:42 PM