C Board  

Go Back   C Board > General Programming Boards > C++ Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 05-15-2009, 12:25 AM   #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--;
}
__________________
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);

Last edited by P4R4N01D; 05-15-2009 at 12:30 AM. Reason: remove some debugging stuff
P4R4N01D is offline   Reply With Quote
Old 05-15-2009, 12:30 AM   #2
C++ Witch
 
laserlight's Avatar
 
Join Date: Oct 2003
Location: Singapore
Posts: 11,338
It looks like you forgot to pass the pointer by reference, so the assignment to a in read() merely changes the local pointer.
__________________
C + C++ Compiler: MinGW port of GCC
Build + Version Control System: SCons + Bazaar

Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
laserlight is offline   Reply With Quote
Old 05-15-2009, 12:43 AM   #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".
__________________
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);

Last edited by P4R4N01D; 05-15-2009 at 12:44 AM. Reason: read -> written
P4R4N01D is offline   Reply With Quote
Old 05-15-2009, 12:46 AM   #4
C++ Witch
 
laserlight's Avatar
 
Join Date: Oct 2003
Location: Singapore
Posts: 11,338
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?
__________________
C + C++ Compiler: MinGW port of GCC
Build + Version Control System: SCons + Bazaar

Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
laserlight is offline   Reply With Quote
Old 05-15-2009, 12:54 AM   #5
Algorithm Dissector
 
iMalc's Avatar
 
Join Date: Dec 2005
Location: New Zealand
Posts: 2,733
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
iMalc is offline   Reply With Quote
Old 05-15-2009, 12:56 AM   #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);
P4R4N01D is offline   Reply With Quote
Old 05-15-2009, 02:04 AM   #7
Kernel hacker
 
Join Date: Jul 2007
Location: Farncombe, Surrey, England
Posts: 15,686
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.
matsp is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Forum Jump

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


All times are GMT -6. The time now is 09:27 AM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.2

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