|
-
Nov 11th, 2002, 07:55 PM
#1
Thread Starter
Stuck in the 80s
[Resolved] Is there a better way?
I just spent forever finding a way to do this:
Code:
#include <iostream>
using namespace std;
double *incArray(double *arr);
int main() {
double *vars;
for (int i = 0; i < 4; i++) {
vars = incArray(vars);
vars[i] = i;
cout << vars[i] << endl;
}
cout << endl << "After: " << endl << endl;
for (i = 0; i < 4; i++) {
cout << vars[i] << endl;
}
return 0;
}
double *incArray(double *arr) {
double *arrtemp = arr;
arr = new double[sizeof(arr)];
for (int i = 0; i < sizeof(arrtemp); i++) {
arr[i] = arrtemp[i];
}
return arr;
}
Is that good or is there a better way?
Last edited by The Hobo; Nov 12th, 2002 at 12:09 PM.
-
Nov 12th, 2002, 03:15 AM
#2
Fanatic Member
What do you want to do? I can't deduct that from the code.
But I think you're doing something wrong in the incArray function. You're taking the size of an unintialized pointer. That doesn't work here. (Although you can except that it will return the value 4).
Besides, if you initialize the size of an array with 'new', you should 'delete' it after usage, in order to free the claimed memory.
-
Nov 12th, 2002, 10:51 AM
#3
Thread Starter
Stuck in the 80s
I'm just trying to create a dynamic array and write a function to increase its size.
-
Nov 12th, 2002, 10:52 AM
#4
Monday Morning Lunatic
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
-
Nov 12th, 2002, 11:00 AM
#5
Thread Starter
Stuck in the 80s
Is this better?
Code:
#include <iostream>
using namespace std;
double *incArray(double *arr);
int main() {
double *vars;
vars = new double[1];
vars[0] = 22;
for (int i = 1; i < 5; i++) {
vars = incArray(vars);
vars[i] = i;
cout << vars[i] << endl;
}
cout << endl << "After: " << endl << endl;
for (i = 0; i < 5; i++) {
cout << vars[i] << endl;
}
return 0;
}
double *incArray(double *arr) {
double *arrtemp = arr;
arr = new double[sizeof(arr)];
for (int i = 0; i < sizeof(arrtemp); i++) {
arr[i] = arrtemp[i];
}
delete[] arrtemp;
return arr;
}
I tried also deleting vars in main(), but it gave me a debug error.
-
Nov 12th, 2002, 11:00 AM
#6
Thread Starter
Stuck in the 80s
Originally posted by parksie
Why not use a vector?
because I have no idea what vector is.
-
Nov 12th, 2002, 11:03 AM
#7
Monday Morning Lunatic
Search the forums, but basically, it's a dynamic array. It's fast, and very easy to use.
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
-
Nov 12th, 2002, 11:25 AM
#8
Thread Starter
Stuck in the 80s
Originally posted by parksie
Search the forums, but basically, it's a dynamic array. It's fast, and very easy to use.
Okay. I'm convinced.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|