Like Tree1Likes
  • 1 Post By c99tutorial

Help with some syntax

This is a discussion on Help with some syntax within the C Programming forums, part of the General Programming Boards category; Hello, I have not been programming for very long at all, I've been working my way through a book, reading ...

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

    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:
    Code:
    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
    Posts
    1,097
    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

    Code:
    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

    Code:
    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:

    Code:
    double *ptr = malloc(n * sizeof(*ptr));
    Last edited by c99tutorial; 02-17-2013 at 04:38 PM.
    Salem likes this.

  3. #3
    Registered User Alexis's Avatar
    Join Date
    Jan 2013
    Posts
    2
    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, 09:56 AM
  2. Help with syntax please.
    By chrismcc35 in forum C Programming
    Replies: 4
    Last Post: 03-04-2008, 06: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21