#include <iostream>
usingnamespace std;
bool doubleCapacity(int& *list, int& size)
{
list = int newList;
size = int newSize;
returntrue; // success
}
int main()
{
cout << "Enter the size of the array: ";
int size;
cin >> size;
int *list = newint [size]
int size2 = size *2;
int list2;
doubleCapacity(size2,list2);
return 0;
}
I have a few errors, but the whole point is the user enter any int number and i'm supposed to make a function to double that number and make a new array. Is that even close to what i'm doing?
Ummm... no. That won't compile. What makes you think that line 6 creates a new array? I don't see a "new" keyword or an array operator. (See line 18.) And you are not deallocating the old array, so you would have a memory leak. And you changed the function signature -- it no longer passes an int* by reference. It passes a pointer to an int reference?!? (I don't think I understand what that would even mean.)
Well i simplified everything up to this right here
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
usingnamespace std;
int main()
{
int* m; int num, count = 0, capacity = 5;
m = newint[capacity];
int newsize = 10;
int *p = newint[newsize];
for (int i = 0; i < capacity; i++)
p[i] = m[i];
delete[] m;
return 0;
}
That work like how i wanted, but now i have to seperate it in to functions
You probably know this, but you still need to get input from the user. Separating it into functions from there shouldn't be that hard. If you have particular errors that happen when you try, you can ask about that and we can try to help.
#include <iostream>
usingnamespace std;
int* doubleCapacity(int *list, int size)
{
int newsize = size *2;
int *p = newint[newsize];
for (int i = 0; i < size; i++)
{
p[i] = list[i];
}
delete[] list;
return p;
}
int main()
{
cout << "Enter the size of the array: ";
int size;
cin >> size;
int *list = newint[size];
int doubleSize = size * 2;
doubleCapacity(list, doubleSize);
return 0;
}
I tested by entering a couple numbers into the array and cout it. Then invoked the function and it came back out 5 more numbers. I"m super happy right now =D
You should be causing a segfault or bus error. You most likely will if your original array is big enough. You create a list of "size", then double it, then pass doubleSize to the doubleCapacity() function. The function then doubles the size again and creates an array 4 times the original size. You then copy twice as many elements as actually exist from the first to the second.