Thread: allocating memory for char* array

  1. #1
    Registered User
    Join Date
    Jun 2003
    Posts
    5

    allocating memory for char* array

    A few questions.

    I know how to allocate memory for say 5 words that contain 10 characters each.
    say:

    char* wrdArray[5];

    for (int count = 0; count < 5; count ++)
    {
    wrdArray[count] = new char[10];
    }

    strcpy(wrdArray[0], "Here is the first string.");
    cout << wrdArray[0];
    ..
    .. etc.


    but how can i allocate memory/is it possible? for predefined words
    that are of different lengths

    using:
    char** wrd = { "..", ".. " }; // can i use this ?? how ??

    char* wrd[5] = { "these", "words", " need", "memory", "???" };

    if in the second case, do i have to allocate memory?, how would i go about it?, do i have to use a for loop and allocate memory individually, can i do a group allocate/deallocate?
    such as:
    free(wrd);

    any ideas would be great.

    thanks.

  2. #2
    Registered User
    Join Date
    May 2003
    Posts
    148

    Re: allocating memory for char* array

    Code:
    char* wrdArray[5];
    
    for (int count = 0; count < 5; count ++)
    {
        wrdArray[count] = new char[10];
    }
    
    strcpy(wrdArray[0], "Here is the first string."); //Bufferoverflow
    Code:
    char* wrd[5] = { "these", "words", " need", "memory", "???" };
    There is a const missing.
    Code:
    const char* wrd[5] = { "these", "words", " need", "memory", "???" };
    Fine.Now you have an array of 5 constant char pointer,with memory allocated by the compiler,so don't call free on it.

    You can copy the array
    Code:
    char *myWrds[5];
    for(int i = 0;i < 5;i++)
    {
        myWords[i] = new char[strlen(wrd[i]) + 1];
        strcpy(myWrds[i],wrd[i]);
    }

  3. #3
    Registered User
    Join Date
    Jun 2003
    Posts
    5
    thanks, that has it alot clearer

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems with shared memory shmdt() shmctl()
    By Jcarroll in forum C Programming
    Replies: 1
    Last Post: 03-17-2009, 10:48 PM
  2. To find the memory leaks without using any tools
    By asadullah in forum C Programming
    Replies: 2
    Last Post: 05-12-2008, 07:54 AM
  3. Assignment Operator, Memory and Scope
    By SevenThunders in forum C++ Programming
    Replies: 47
    Last Post: 03-31-2008, 06:22 AM
  4. allocating memory in constructor
    By Micko in forum C++ Programming
    Replies: 3
    Last Post: 08-25-2004, 07:45 AM
  5. Replies: 5
    Last Post: 11-24-2002, 11:33 PM