allocating mem for an array

This is a discussion on allocating mem for an array within the Linux Programming forums, part of the Platform Specific Boards category; I'm curious as to how I would allocate memory as needed for a multideminsional array? ex: Code: char command_names[*][20]; //improper, ...

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    44

    allocating mem for an array

    I'm curious as to how I would allocate memory as needed for a multideminsional array? ex:

    Code:
    char  command_names[*][20];  //improper, yes I know
    
    command_names=malloc(blah blah); //i got no clue

    Any help? Do you understand what I'm doing? Its a character string, and I need to be able to store as much as that is needed.

    Thanks.
    [Strut]

    I lay on my bed watching the stars, and I thought to myself... Where the hell is my roof?

  2. #2
    Im back! shaik786's Avatar
    Join Date
    Jun 2002
    Location
    Bangalore, India
    Posts
    345
    >char command_names[*][20]; //improper, yes I know
    Is totally wrong in the declaration itself. If you want to declare 20 pointers to type 'char *', then this is the way you do it:
    Code:
    char *command_name[20];
    Now that you declared 20 pointers, they are randomly pointing to some memory location in you physical RAM. You need to make them point to your program's address space, so you use malloc() to allocate memory in your address space, and make these pointers point to the returned allocated space by. To allocate, you do:
    Code:
    command_name[0] = malloc(100);    /*   100 bytes are retrned   */
    command_name[1] = malloc(100);
    .
    .
    .

  3. #3
    Registered User
    Join Date
    Sep 2001
    Posts
    44
    shaik, yes I know the decleration was all wrong. I wrote it like that to show that the[*] wasn't known. As in I need to allocate the[*] to how ever character strings I may need.


    I appreciate both your replies. Thank you for your help. I'll see what I can.
    [Strut]

    I lay on my bed watching the stars, and I thought to myself... Where the hell is my roof?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-29-2009, 08:25 PM
  2. Dynamically Allocating a 2D Array.
    By LightsOut06 in forum C Programming
    Replies: 17
    Last Post: 10-09-2005, 01:55 AM
  3. Dynamicly allocating an array of pointers
    By kzar in forum C Programming
    Replies: 2
    Last Post: 05-05-2005, 05:50 PM
  4. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 09:31 AM
  5. allocating a single array
    By lambs4 in forum C Programming
    Replies: 1
    Last Post: 01-19-2002, 09:32 PM

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