Thread: Dynamic Array Allocation function

  1. #1
    HelpingYouHelpUsHelpUsAll
    Join Date
    Dec 2007
    Location
    In your nightmares
    Posts
    223

    Dynamic Array Allocation function

    I have written a function to read in a variable number of ints into an array, & after this is called I print out the values in the array that were read in in main(). When i print out the contents of the array however, most of f the elements are garbage and bear no resemblance to what values I entered in. I think the array it is modifing is not modifing the size for the calling function but I am not sure how to fix it as the function also returns the number of elements read into the array. The array has expected values inside the read function and returns the correct value for n. Here is code:

    Code:
    #include <iostream>
    
    using namespace std;
    
    void read(int *a, int &n);
    // read the first n elements of array a
    
    int SIZE = 5;
    
    int main()
    {
    
        int *list1 = new int[SIZE];
        int *list2 = new int[SIZE];
        int noeles1=0, noeles2, test1, test2;
    
        read(list1, noeles1);
    
        read(list2, noeles2);
    
        cout << "List 1: " << endl;
        for (test1=0; test1<noeles1; test1++) {
            cout << list1[test1];
            cout << " ";
        }
    
        cout << "\nList 2: " << endl;
        for (test2=0; test2<noeles2; test2++) {
            cout << list2[test2];
            cout << " ";
        }
    
        return 0;
    }
    
    // write the body of following functions
    
    void read(int *a, int &n)
    {
    	SIZE = 5;
    	int k;
    	cout << "Enter values:" << endl;
    		n=0;
    		do {
    			if (n<SIZE) cin >> a[n];
    			else {
    				SIZE *= 2; //double array
    				int *temp = new int[SIZE];
    				for (k = 0; k<SIZE; k++) temp[k] = a[k];
    				delete [] a;
    				a = temp;
    				cin >> a[n];
    			}
    		} while (a[n++] != -1);
    	    n--;
    }
    Last edited by P4R4N01D; 05-15-2009 at 12:30 AM. Reason: remove some debugging stuff
    long time no C; //seige
    You miss 100% of the people you don't C;
    Code:
    if (language != LANG_C && language != LANG_CPP)
        drown(language);

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    It looks like you forgot to pass the pointer by reference, so the assignment to a in read() merely changes the local pointer.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    HelpingYouHelpUsHelpUsAll
    Join Date
    Dec 2007
    Location
    In your nightmares
    Posts
    223
    Thanks for the quick reply, I thought passing a pointer to int was passing by reference. Would changing the function to void read(int **a, int &n) pass by reference (as int &*a didn't work and int a would just be an int). If I change a to be passed as above & change every occurance of a to *a I get a runtime error: "the memory couldn't be written".
    Last edited by P4R4N01D; 05-15-2009 at 12:44 AM. Reason: read -> written
    long time no C; //seige
    You miss 100% of the people you don't C;
    Code:
    if (language != LANG_C && language != LANG_CPP)
        drown(language);

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    Quote Originally Posted by P4R4N01D
    Would changing the function to void read(int **a, int &n) pass by reference (as int &*a didn't work and int a would just be an int).
    It would simulate pass by reference, but what I had in mind:
    Code:
    void read(int *&a, int &n)
    Actually, to emphasize type, I would write it as:
    Code:
    void read(int*& a, int& n)
    By the way, why are you not using std::vector<int> instead?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by P4R4N01D View Post
    Thanks for the quick reply, I thought passing a pointer to int was passing by reference. Would changing the function to void read(int **a, int &n) pass by reference (as int &*a didn't work and int a would just be an int). If I change a to be passed as above & change every occurance of a to *a I get a runtime error: "the memory couldn't be written".
    That's because you tried to declare a pointer to a reference which is illegal. You need a reference to a pointer instead.

    Types are read right to left (well there's more to it than that when you get more complex examples, but that's true enough for you, for now).
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  6. #6
    HelpingYouHelpUsHelpUsAll
    Join Date
    Dec 2007
    Location
    In your nightmares
    Posts
    223
    Quote Originally Posted by laserlight View Post
    By the way, why are you not using std::vector<int> instead?
    As I have not learnt about vectors yet, I didn't even think about using them. Breifly looking at a reference on them I can see how they would be useful as an alternate method. Another reason why I used this approach was to modify an existing program that read in a fixed number of integers. Thanks for your help.
    long time no C; //seige
    You miss 100% of the people you don't C;
    Code:
    if (language != LANG_C && language != LANG_CPP)
        drown(language);

  7. #7
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Can I also suggest that you modify the
    Code:
    			if (n<SIZE) cin >> a[n];
    			else {
    				SIZE *= 2; //double array
    				int *temp = new int[SIZE];
    				for (k = 0; k<SIZE; k++) temp[k] = a[k];
    				delete [] a;
    				a = temp;
    				cin >> a[n];
    			}
    so that you only have one cin >> a[n] - there is no need to do that twice. Just change the condition to test FIRST if there is enough space, and then allocate more space if needed.

    Also, you should not copy the NEW size from a[k], as that is outside the size of the original allocation, so you probably need another variable to hold the original (or new) size until you have updated the content.

    Finally, I would suggest that you do not use a global variable for size - there is a bug in your current code because of the size for the frist array being changed, so that if you enter 100 values in the first set, the second set will overwrite the end of your allocation after the 5 first elements have been entered. You need to keep track of the size of each array, not have one variable for both!

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointer to function and dynamic allocation
    By cfdprogrammer in forum C Programming
    Replies: 7
    Last Post: 07-08-2009, 10:36 AM
  2. sorting number
    By Leslie in forum C Programming
    Replies: 8
    Last Post: 05-20-2009, 04:23 AM
  3. pointer to array with dynamic allocation
    By cfdprogrammer in forum C Programming
    Replies: 22
    Last Post: 04-07-2009, 09:56 AM
  4. dynamic allocation of 2d array
    By owi_just in forum C Programming
    Replies: 4
    Last Post: 05-09-2005, 12:50 AM
  5. c++ linking problem for x11
    By kron in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2004, 10:18 AM