Thread: dynamic memory allocation char array

  1. #1
    Waxy-Dock
    Join Date
    Mar 2005
    Posts
    69

    dynamic memory allocation char array

    Hi,

    Im trying to dynamically allocated the number of elements to my char array. Whats the best way to do this.. maybe something like this?

    int sizeofarray = 10;

    char *myarray = malloc(sizeof(char)*sizeofarray);

    then i need to access the array normally like myarray[9] = 'g';

    am i on the right track?

  2. #2
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    yep, but remember that sizeof(char) == 1, so its pretty redundant, for example:

    Code:
    char * myarray;
    const unsigned short int myarray_size = 10;
    
    if((myarray = malloc(myarray_size)) == NULL)
    {
        perror("malloc failed");
        exit(1);
    }
    /* do as you will with myarray, remember to stay in bounds tho! */

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Unless you adopt the idiomatic
    p = malloc ( num * sizeof *p );

    which works for all types, and saves you having to think about exceptions to rules who's only side effect is to save a bit of typing.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Creating a dynamic array of char
    By Sharke in forum C++ Programming
    Replies: 12
    Last Post: 06-23-2009, 12:25 AM
  2. Dynamic memory allocation
    By Luciferek in forum C++ Programming
    Replies: 118
    Last Post: 10-02-2008, 11:34 AM
  3. get keyboard and mouse events
    By ratte in forum Linux Programming
    Replies: 10
    Last Post: 11-17-2007, 05:42 PM
  4. Dynamic memory allocation
    By amdeffen in forum C++ Programming
    Replies: 21
    Last Post: 04-29-2004, 08:09 PM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM