Array Allocator

Array Allocator

My teacher wantes me to Write a function that dynamically allocates an array of doubles and returns a pointer to the new array. Also The function should accept an integer parameter that indicates the size of the new array. can you guys pls give me some tips on how Write a main program to test.

Thanks guys
can you guys pls give me some tips on how Write a main program to test.

Well the main program just needs to call this function and use it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

double* make_double_array(int size);

int main() {
    int const length = 20;
    double *ptr = make_double_array(length);
    int sum = 0;
    for(int i = 0; i < length; i++) {
        ptr[i] = i+1;
        sum += ptr[i];
    }
    std::cout << "The sum of 1 to " << length << " is " << sum << std::endl;
    //free the memory of ptr, unless you want to have a memory leak
    return 0;
}

double* make_double_array(int size) {
     double *temporary;

     //you should put your function definition here

     return temporary;
}

I am going to assume that you actually wanted help creating a dynamic array. Here is a link to a tutorial on this site showing how to create one:
http://www.cplusplus.com/doc/tutorial/dynamic/
Hey thanks for the tips. im still working on this and got really confused. can anyone help me out to finish this thing. appreciate it

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

double* make_double_array(int size);

int main() {
	int const length = 20;
	double *ptr = make_double_array(length);
	
	std::cout << "The sum of 1 to " << length << " is " << "sum" << std::endl;
	
	return 0;
}

double* make_double_array(int size) {
	double *temporary;
	int sum = 0;
	for (int i = 0; i < size; i++) {
		ptr[i] = i + 1;
		sum += ptr[i];
	}

	return temporary;

}
I think you need to read how scoping works in C++. ptr is not a variable that make_double_array can "see" in its scope.
scoping: http://www.cplusplus.com/doc/tutorial/namespaces/

After that you should be able to write a function that can dynamically allocate a double array.
dynamic memory syntax: http://www.cplusplus.com/doc/tutorial/dynamic/
Last edited on
Topic archived. No new replies allowed.