Dynamic array allocation

This is a discussion on Dynamic array allocation within the C++ Programming forums, part of the General Programming Boards category; Here is the exercise I am trying to complete: Write a function that takes a char* argument. Using new, dynamically ...

  1. #1
    Registered User
    Join Date
    Mar 2010
    Posts
    7

    Dynamic array allocation

    Here is the exercise I am trying to complete:

    Write a function that takes a char* argument. Using new,
    dynamically allocate an array of char that is the size of
    the char array thatís passed to the function. Using array
    indexing, copy the characters from the argument to the
    dynamically allocated array (donít forget the null
    terminator) and return the pointer to the copy. In your
    main( ), test the function by passing a static quoted
    character array, then take the result of that and pass it
    back into the function. Print both strings and both
    pointers so you can see they are different storage. Using
    delete, clean up all the dynamic storage.
    I have a basic understanding of pointers, but I'm totally new to dynamic memory, so I really had no idea what to do with this one. Here's my failing code:

    Code:
    #include <iostream>
    using namespace std;
    
    char dynChar(char* a, int size){
        char* b = new char[size];
        for (int i=0; i<size; i++)
            b[i] = a[i];
        return *b;
        delete[] b;
    }
    
    int main(){
        char c[] = "Hello world!";
        char d[] = dynChar(c,13); //line 14, with the error
        cout << d;
        return 0;
    }
    There are two issues with this code. 1) I don't know how to find the size of the array, so the function has to be given the length of the array. How can I find an array's size?

    2) It won't compile. It gives an error at line 14, saying the initializer can't determine the size of d. I don't really know what that means. Could someone help me out with this?

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Code:
        char d[] = dynChar(c,13); //line 14, with the error
    d should be a pointer.
    Code:
    char dynChar(char* a, int size){
        char* b = new char[size];
        for (int i=0; i<size; i++)
            b[i] = a[i];
        return *b;
       delete[] b;
    }
    dynChar should return a pointer.

    return() is the end of a function. Commands after an unqualified return() are superfluous and will not be executed. Besides which, you are returning the new C-string pointer -- why would you want to delete it?
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Registered User
    Join Date
    Mar 2010
    Posts
    7
    Making dynChar return a pointer and changing d to a pointer worked, though I still can't figure out how to get the array size from the inputted array.

    I put the delete[] after return because the exercise requires the allocated space to be deallocated, and I assumed because it was allocated in the function that I would need to deallocate it in the function. As I said before, I'm very new to dynamic memory.

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    If you
    Code:
    #include <cstring>
    you can use strlen() to get the length of a C-string. This DOES NOT include the null terminator, so the normal formula for allocation is strlen(str)+1.

    Quote Originally Posted by Maulrus View Post
    I put the delete[] after return because the exercise requires the allocated space to be deallocated, and I assumed because it was allocated in the function that I would need to deallocate it in the function. As I said before, I'm very new to dynamic memory.
    Delete the memory after you are finished using it:
    Code:
    int main(){
        char c[] = "Hello world!";
        char *d = dynChar(c,13); //line 14, with the error
        cout << d;
        delete[] d;
        return 0;
    }
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  5. #5
    Registered User
    Join Date
    Mar 2010
    Posts
    7
    Okay, thanks. Let me see if I understand: the pointer inside the function IS the object in main(), so if you allocate the space for it in a function, it can be deallocated outside of the function?

    Also, I got it working without strlen (I don't want to use any functions the book hasn't introduced yet):

    Code:
    char* dynChar(char* a){
        int size = 0;
        char c = '0';
        while(c != '\0'){
            c = a[size];
            size++;
        }
        cout << size << endl;
        char* b = new char[size];
        for (int i=0; i<size; i++)
            b[i] = a[i];
        return b;
    }

  6. #6
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Maulrus View Post
    Okay, thanks. Let me see if I understand: the pointer inside the function IS the object in main(), so if you allocate the space for it in a function, it can be deallocated outside of the function?
    Yes, that is a major purpose/function of pointers. A pointer contains the starting address of a block of memory (well, it can also be NULL, etc). So you refer to the block with the pointer. If you think about it a bit, you may be able to see how you could have an allocated block without a pointer (eg, if dynChar did not return anything). That means the block can no longer be deleted (aka, freed), because you do not have any variable/pointer to refer to it with, and results in a memory leak.

    Also, I got it working without strlen (I don't want to use any functions the book hasn't introduced yet):
    That's great. Here's a variation to contemplate:
    Code:
    char* dynChar(char* a){
        int size = 0;
        char c;
        while((c = a[size])) size++;
        size++;
    '\0' is equal to 0 by the standard. Bracketing an assignment -- (c=a[size]) -- makes it a truth test of the result.* The only value which is false in C/C++ is 0. So this will increment size until c == '\0'. Then add one -- size++ -- to include it.

    * ie, the variable assigned to, in this case, "c".
    Last edited by MK27; 03-09-2010 at 04:20 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  7. #7
    Registered User
    Join Date
    Mar 2010
    Posts
    7
    Oh right, I forget to add an extra size++ for the \0 character. Thanks for all the help with this! I spent a good amount of time in class today sitting and trying to get this to work, and I have a much better understanding of arrays and dynamic memory now.

  8. #8
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    4,359
    Code:
    char* dynChar(char* a){
        int size = 0;
        char c;
        while((c = a[size])) size++;
        size++;
    O_o

    Why not simplify it further?

    The parameter needs to be `const char *' if you don't intend to modify the data.

    Soma

    Code:
    int size(0);
    while(a[size++]);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic memory allocation
    By Luciferek in forum C++ Programming
    Replies: 118
    Last Post: 10-02-2008, 12:34 PM
  2. Dynamic Array Resizing
    By dld333 in forum C++ Programming
    Replies: 13
    Last Post: 11-04-2005, 12:13 AM
  3. dynamic array
    By linuxdude in forum C Programming
    Replies: 5
    Last Post: 07-13-2004, 03:33 AM
  4. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 09:31 AM
  5. dynamic allocation question
    By vale in forum C++ Programming
    Replies: 1
    Last Post: 08-26-2001, 05:23 PM

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