Allocate memory in a function and call from main

So my assignment is to create a program that calls for a function in main that dynamically allocates an array[3] and then have pointers with multiple levels of indirection and pass them by reference so they are not lost after the function. I am stuck on this part and can't figure out why this is wrong if someone would please explain it to me.
Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <array>
#include <iomanip>
#include <string>

using namespace std;

//Function Prototypes

void input(int&,int&);
void printResults(int&, int&);
void close(char&);
void allocation(int&, int&, int&, int&);


// Begins Program

int main() 
{

	//Declare Local Variables
	int n,n1; 
	char ch;
	int *arr, *x, **y, ***z, ***q;
	allocation(*arr, *x, **y, ***z); // Calls function to Dynamically Allocate memory
	input(n,n1); // Calls function to Input Numbers and Validate Non-Negative Numbers
	printResults(n,n1); //Calls function to Display Results 
	close(ch);



}
void allocation(int*& arr, int*& x, int**&y,int***&z)
{
	//Declare Arrays and Pointers
	arr = new int[3];
	x = arr;
	y = &x;
	z = &y;
	//q = **z; // Lost on how to do Q!!!!
}
void printResults (int& n, int& n1 )  // Displays Results *NOT FINISHED*
{
	cout << "You have entered: " << n << setw(10) << n1 << endl;
}
void close(char& ch) 
{
	//Program Termination

	cout << "\n Program Over \n" << endl;
	cout << "Press Enter to end -->" << endl;

	char c1, c2; // Variables to store user input
	c1 = getchar(); // get first input
	c2 = getchar(); // get second input
	if (c1 == '\n' && c2 == '\n') // if post inputs are enter
	exit(1); // exit
}


void input(int& n, int& n1)
{	
	
	// prompts the user for a non-negative numbers (>= 0)
	// reads in the a number and checks
	// keeps re-prompting user if the input is invalid (negative)
	// returns the a non-negative input.
		do
		{
			cout << "Please enter a valid non-negative integer:\n";
			cout << "1)";
			cin >> n;
			cout << "2)";
			cin >> n1;
		} while (n <= 0 || n1 <= 0);
}




Next part is to ask user for two non-negative numbers and then get the length of those numbers and create an array. for the size of each number they input. Then to separate those numbers and add the cross-sums. If someone could point me into the right direction, as I am stuck and don't know what to do.

Thanks,
Sean
Wait, what? I'm confused. Could you post your assignment verbatim?
This assignment looks like its purpose is to show how stupid you can get with pointers if you really try. I always hated assignments where the code was purposely made hard for some stupid reason like this. In the real world, you'd never write this program in this manner. I see what it's doing (I think, just based on what I've read so far). So like if the user gave you 156 and 241 as the two numbers, you'd cross sum each digit. So if you had an array with three elements, index 0 = 1+2 = 3, index 1 = 5+4 = 9, index 2 = 6+1 = 7. This sort of thing is useful for stuff like the game Kakuro, which is sort of like Sudoku but with cross sums. This would be much easier to do without this sort of complication, but I'm guessing your teacher is a horses rear end.
did not fully get your question, but your protocol is not correct, since they are not consistent with your implementation. surely no error now would be thrown by the compiler, since the protocol you have defined has not been used.

but back to your question, say you want to allocate memory in a function and return it back. this is very similar as normal function call. you must understand this
1
2
3
4
5
6
7
8
#include <stdio.h>
void func(int& r) { r = 100; }
void main()
{
    int a;
    func(a);
    printf("%d\n", a);
}

so return an array is almost the same, the protocol is
1
2
3
4
5
6
7
8
9
10
#include <stdio.h>

void func(int*& r) { r = new int[100]; }
void main()
{
    int* a;
    func(a);
    a[8] = 100;
    printf("%d\n", a[8]);
}


this is the example of how to return an array from a function, just as what you are asking.
but this is evil, never try to use it in this way, because,
1. there is no way to know the size of array returned from func, unless you give another reference parameter to show it
2. the caller has no information about whether it should or not to release the array
3. there are do better solutions, say std::vector or std::array in c++ 11
e.g. using vector
1
2
3
4
5
6
7
void func(vector<int>& v) { v.resize(100); }
void main()
{
    vector<int> v;
    func(v);
    for(int i = 0; i < v.size(); i++) { }
}

Last edited on
randisking: pretty much he wants you to use multiple pointers all pointing to the base address of the array[3] created in an allocation function and called from main while the program ask the user ot enter 2 non negative numbers, the program should then get the length of the numbers and allocate 3 arrays. 1 for the 1st set of numbers 2 for the 2nd set of numbers and 3 is to create an array of the larger of the numbers( IE: 123 and 4567 you would create an array[4]. Where im getting confused on is the pointers being passed from a function and creating memory allocation to store and its driving me nuts.
CS M10B - Topic A Project –
Due Wednesday 9/11

Write a program that implements the following diagram:



Use new to allocate any memory wherever it can be used without incurring any memory leaks and will end up implementing the diagram. For the remainder, use already declared pointer variables where that must be done in order to implement the diagram. Thus there will be a mix where some pointers are dynamically allocated and others will simply be assigned addresses of existing variables. It is up to you to determine what the correct mix is. Your program cannot create named identifiers for any unnamed boxes.

The shaded boxes represent pointers. The unshaded horizontal box represents an array of pointers to int. The unshaded vertical arrays represent int arrays of unknown size (as indicated by the vertical ellipses). The size for the first two (starting from the left) are obtained indirectly from the user and are to be dynamically allocated. The rightmost array size will be determined by the program as given below and dynamically allocated.

In fact what is represented is a two dimensional ragged array. That is, the horizontal array represents the first dimension, the rows, while the vertical arrays represent the columns. It is called a ragged array as each column can have a different length. This way of representing a two dimensional array is, in fact, the way that C++ actually handles multidimensional arrays.

In order to capture the sizes of all three of the vertical (column) arrays, you will create an array in main which will hold the array sizes. Element 0 will have the size of the first array, element 1 the second array's size, and element 2 the third size. Use the array class template.

Your program should ask the user for 2 non-negative integer values. Be sure to verify that the values are correct. The program will then allocate the first two arrays where the size of each is the number of digits in the respective values. Each digit is to be put into a separate element. Finally, the last array is to be the size of the larger of the two other arrays. Digits will be added across and the sum stored in the corresponding element of the last array. For example, the value in index 0 in the first (leftmost) array is added to the value in index 0 in the second array. That sum is stored in index 0 in the last array. Run the example program to see what is required. The sum of both numbers will also be obtained.

In your program only refer to the integer array through the pointers represented by x, y, and z. That is, do not use q when referring to an actual integer value or reduce the number of levels of indirection when using parameters or substitute any other variables.

The “Memory Layout for C++ Part 2” document discusses levels of indirection. Each arrow in the above diagram represents a level of indirection. Each level of indirection corresponds to an “*” when using a pointer variable.


Further, your program is to have these functions, at a minimum:
• The allocation function, called from main, which allocates and assigns all the memory except for the 3 lower (column) arrays and the sizes array.
• The input function, called by main. This input function then calls the function which checks to be sure that the input is really a non-negative integer. Calls the function to put the values into the first and second arrays. The input function also puts the sizes of the first two arrays into the sizes array. Use x as the parameter to access the array and use array notation for accessing the arrays.
• The number checking function verifies if that value is a valid non-negative integer. Called by the input function.
• The function to allocate and put an input value into one of the vertical arrays. Called by the input function.
• The summation function, called by main, does the summation. The function will do the cross sums. Use only the arrays, not any other values, such as the original input numbers. Allocates the last array and puts its size into the sizes array. Use y as the parameter to access the array and use pointer (address) notation when using y. (Address notation cannot be used with arrays allocated using the array class template.)
• A display function to display the results. Use z as the parameter to access the array and use pointer (address) notation when using z.
• Remember – no global variables

If the actual parameters for functions are pointers they should not be dereferenced. That is, if y, for example, is being passed to a function it must be passed as a pointer with double indirection.

Remember to deallocate any dynamic memory.

Use & appropriately in parameters. Do not pass by reference where it is not necessary. Use const where appropriate.

Run the example program TopicA.exe. Put in valid as well as invalid values. See what happens when 0 is entered. The "Press enter to end" line is part of the assignment.

Call your source code file TopicA.cpp.

bump
Topic archived. No new replies allowed.