Thread: correct malloc use

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Nov 2004
    Posts
    55

    correct malloc use

    Hi all,
    I 'm having a bit of trouble understanding about the use of malloc for 1d and 2d arrays., and I would appreciate if someone could tell me what is correct. Lets say for 1d arrays, which is correct?

    vector = malloc(length*sizeof(vector));
    or
    vector = malloc(length*sizeof(*vector));
    and for 2d arrays:
    Code:
            matrix=malloc(rows*sizeof(matrix));
            for (i=0; i<columns; i++)
                    matrix[i]=malloc(columns*sizeof(matrix[i]));
    or
    Code:
            matrix=malloc(rows*sizeof(*matrix));
            for (i=0; i<columns; i++)
                    matrix[i]=malloc(columns*sizeof(*matrix[i]));
    I've tried both with gcc and all warnings/pedantic flags on, but both produce the same result (and no warnings) when I put some values in vector and array and then display them.

    I've also seen (assuming vector and matrix are unsigned integers
    Code:
    vector = malloc(length*sizeof(unsigned int*))
    and
    Code:
            matrix=malloc(rows*sizeof(unsigned int *));
            for (i=0; i<columns; i++)
                    matrix[i]=malloc(columns*sizeof(unsigned int));
    Ideally I'd like to avoid this in case I want to chenge the type of vector or matrix eg from float to double.

    Thank you
    Spiros
    Last edited by s_siouris; 05-28-2008 at 05:33 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc() resulting in a SegFault?!
    By cipher82 in forum C++ Programming
    Replies: 21
    Last Post: 09-18-2008, 11:24 AM
  2. Wierd Malloc Problem
    By mohankarthik in forum C Programming
    Replies: 11
    Last Post: 09-17-2008, 02:14 PM
  3. Malloc for extending the size....!
    By patil.vishwa in forum C Programming
    Replies: 5
    Last Post: 09-11-2008, 03:34 AM
  4. the basics of malloc
    By nakedBallerina in forum C Programming
    Replies: 21
    Last Post: 05-20-2008, 02:32 AM
  5. Random number + guessing game trouble
    By Ravens'sWrath in forum C Programming
    Replies: 16
    Last Post: 05-08-2007, 03:33 AM