I am trying to code a class that represents a set of integers. It's a homework assignment but for the life of me I cannot figure out this issue.
In the class "IntSet", I have two private variables; one is a pointer to an array the other is the size of the array. I can create objects of this class and they work as intended. But I have this function named "join" that returns an object of the IntSet class. It essentially concatenates the arrays together then uses that array to create the returning object.
Here is my code:
#include <iostream>
using namespace std;
class IntSet {
int * arrPtr;
int arrSize;
public:
//Default Constructor
IntSet() {
int arr[0];
arrPtr = arr;
arrSize = 0;
}
//Overloaded Constructor
IntSet(int arr[], int size) {
arrPtr = arr;
arrSize = size;
}
//Copy Constructor
IntSet(const IntSet &i) {
arrPtr = i.arrPtr;
arrSize = i.arrSize;
}
/*
* Returns a pointer to the first
* element in the array
*/
int* getArr() {
return arrPtr;
}
int getSize() {
return arrSize;
}
IntSet join(IntSet &setAdd) {
//Make a new array
int temp[arrSize + setAdd.getSize()];
//Add the the values from the current instance's array pointer
//to the beginning of the temp array
for (int i = 0; i < arrSize; i++) {
temp[i] = *(arrPtr + i);
}
//Add the values from the passed in object's array pointer
//to the temp array but after the previously added values
for (int i = 0; i < setAdd.getSize(); i++) {
temp[i + arrSize] = *(setAdd.getArr() + i);
}
//Create a new instance that takes the temp array pointer and the
//size of the temp array
IntSet i(temp, arrSize + setAdd.getSize());
//Showing that the instance before it passes works as expected
cout << "In join function:" << endl;
for (int j = 0; j < i.getSize(); j++) {
cout << *(i.getArr() + j) << endl;
}
//Return the object
return i;
}
};
int main() {
//Make two arrays
int arr1[2] = {2 ,4};
int arr2[3] = {5, 2, 7};
//Make two objects normally
IntSet i(arr1, 2);
IntSet j(arr2, 3);
//This object has an "array" that has arr1 and arr2 concatenated, essentially
//I use the copy constructor here but the issue still occurs if I instead use
//Inset k = i.join(j);
IntSet k(i.join(j));
//Shows the error. It is not the same values as it was before it was returned
cout << "In main function:" << endl;
for (int l = 0; l < k.getSize(); l++) {
cout << *(k.getArr() + l) << endl;
}
return 0;
}
The program compiles and the output as of now is:
In join function:
2
4
5
2
7
In main function:
10
0
-2020743083
32737
-2017308032
I don't know why but the 10 and 0 are always the same every time I recompile and run. Also, if I print out the address of the pointer rather than the value(in both the join function and the main function), I get the same memory address.
Sorry if I misuse terms, I come from a java background, so pointers and such are a little new to me. If any clarification is needed, please ask.
Thanks in advance.
int temp[arrSize + setAdd.getSize()];
This is a local array, its lifetime ends once the function returned.
IntSet i(temp, arrSize + setAdd.getSize());
Here you are constructing an IntSet with this array. In fact the constructor simply changes a member pointer to the value of temp:
IntSet(int arr[], int size) {
arrPtr = arr;
arrSize = size;
}
As a result, since the lifetime of the object that temp and consequently also i.arrPtr is pointing to ends after leaving join, you will have a wild pointer. Dereferencing this pointer later in main invokes undefined behavior.
You need to allocate the array dynamically with new[] and delete it later with delete[]. The same goes for your constructors. Also note that if you use new[] in join and delete[] in the destructor, then you also have to make sure that the copy constructor actually copies the array (create new array with new[] and copy contents). If you simply assign the pointer then both the source and destination object will point to the same array and they will also both try to delete it at deconstruction, again invoking undefined behaviour.
But since this C++, you might as well use a std::vector which does all of this for you. (or std::set if you actually want a integer set)
The quickest fix with your code is to change
int temp[arrSize + setAdd.getSize()];
into this
int * temp = new int[arrSize + setAdd.getSize()];
The thing is that you allocated temp on the stack, so when join() returns that memory is releases. By allocating memory on the heap (as per the fix) the memory is not released when join() returns.
There are other things wrong with your code -- depending on the point of the assignment. I think most of these will be fixed when you consider the implications of having memory on the heap.
Related
What's the meaning of the code below?
int **matrix = new int*[n]
What's the difference here between matrix and int*[n]?
It is an array of 'n' pointers, for which memory can be allocated and initialized in loop.
If n is 3, it is an array of 3 elements and each is pointer to int, can point to set of array of integer values like below.
matrix[0] -> Ox001 points to array of int [ 1 2 3 4]
matrix[1] -> Ox017 [ 5 6 7 8]
matrix[2] -> Ox024 [ 9 10 11 12]
Sample code like this
int **m = new int*[3];
for(auto i=0; i < 3; i++)
{
m[i] = new int[3];
for(auto j=0; j < 3; j++)
m[i][j] = 0;
}
for(auto i=0; i < 3; i++)
{
m[i] = new int[3];
for(auto j=0; j < 3; j++)
cout << m[i][j];
cout << "\n";
}
for instance there is cricket team and you need
Since you have Cricket* team;, this indicates you have one of two possible
situations:
1) a pointer to a single CricketPlayer (or any derived) type
2) a pointer to an array of CricketPlayer (but not derived) types.
What you want is a pointer to an array of CricketPlayer or derived types. So you
need the **.
You'll also need to allocate each team member individually and assign them to the array:
// 5 players on this team
CricketPlayer** team = new CricketPlayer*[5];
// first one is a bowler
team[0] = new Bowler();
// second one is a hitter
team[1] = new Hitter();
// etc
// then to deallocate memory
delete team[0];
delete team[1];
delete[] team;
In your query,
It can be understood as
int *matrix[]=new int*[n];
SO there are n pointers pointing to n places.
Because
int *foo;
foo=new int[5];
will also create 5 consecutive places but it is the same pointer.
In our case it is array of pointers
You need to notice some thing as follows:
int *p means that p is a pointer that points to an int variable or points to an array of int variables.
int* *p means that p is a pointer that points to an int* variable or points to an array of int* variables.
new int[5] is an array of 5 int variables.
new int*[5] is an array of 5 int* variables.
In this case, matrix is the second type so it can point to an array of int* variables so the statement:int **matrix = new int*[n] is legal
It means that you have declared a double pointer(of type int) called matrix and allocated an array of n int* pointers. Now you can use matrix[i] as an int* pointer (0 <= i < n). Later you might want to allocate memory to individual pointers as well like matrix[i] = new int[size];(size is an int or more appropriately size_t)
matrix is an object of type int **. This type is a pointer to pointer to int.
On the other hand, int * is a type, a pointer to int.
The expression:
new int*[n]
creates n adjacent objects of type int * somewhere in memory and returns a pointer to the first of them. In other words, it allocates and constructs n pointers to int; and returns a pointer to the first. Since the first (and each of them) are int *, the pointer pointing to the first is, in turn, of type int **.
It would be absolutely clear if you remember the operator associativity and precedence.
Going by that int *[n] will be interpreted by compiler : as array of " n pointer to integers".(as [ ] has greater precedence than *, so for easy understanding, compiler interprets it that way.).
Now comming to other side int ** matrix is pointer to pointer.
When you created an array of pointer,you basically have the address of the first location ,here first location stores an pointer to integer.
So,when you are storing the address of the first address of such array you will need pointer to a pointer to point the whole array.
//code for passing matrix as pointer and returning as a pointer
int ** update(int ** mat)
{
mat[0][1]=3;
return mat;
}
int main()
{ int k=4;
int **mat = new int*[k];
for(auto i=0; i < k; i++)
{
mat[i] = new int[k];
for(int j=0;j<k;j++)
{
if(i==j)
mat[i][j]=1;
else
mat[i][j]=0;
}
}
mat=update(mat);
for(auto i=0; i < k; i++)
{
for(auto j=0; j < k; j++)
cout << mat[i][j];
cout << "\n";
}
return 0;
}
I'm working on an assignment involving string pointers. There are two functions. The first takes in an array of strings, places the address of each element into a separate array, and then returns the pointer to that array. The second function takes the pointer that was returned and prints out the elements of the original array with just the pointer. But when I test it, the dereferenced string** ptrToPtr is different in each pointer. I want to know why
Here is Function 1:
string** arrayOfPtrs(string arr[], int size)
{
string* ptrArray; //The array of string pointers
string** ptrToPtr; //A pointer to the array of string pointers
ptrArray = new string[size];
//ptrArray = arr;
int i = 0;
while (i < size)
{
ptrArray = &arr[i];
i++;
ptrArray++;
}
ptrToPtr = &ptrArray;
return ptrToPtr;
}
Here is Function 2:
void outputArray(string** arr, int size)
{
int count = size; //An int variable that stores the size of array
string* ptr = *arr; //A pointer that stores the address to the last element
//in the string pointer array
while (count > 0)
{
cout << *(ptr - count) << " ";
count--;
}
cout << endl;
}
And here is part of main():
string strArr[] = { "echo", "charlie", "delta", "bravo", "delta" };
string** strPtrs;
strPtrs = arrayOfPtrs(strArr, 5);
cout << "Actual results: ";
outputArray(arrayOfPtrs(strArr, 5), 5);
cout << endl << endl;
I'm I going wrong anywhere? Or is there a better way to deference a pointer to a string pointer?
Here is a similar program ran completely in main:
int main()
{
string words[30];
string* s;
s = new string[30];
string** t;
createArray(30, words);
int num = 0;
t = &s;
while (num < 30)
{
s = &words[num];
num++;
s++;
}
string* u = *t;
int j = 30;
for (int i = 0; i < 30; i++)
{
cout << "*(s - " << j << ") - " << *(s - j) << endl;
cout << "words[ " << i << " ] - " << words[i] << endl;
cout << "*(u - " << j << " ) - " << *(u - j) << endl << endl;
j--;
}
}
And this program works perfectly. Any ideas?
This is incorrect:
while (i < size)
{
ptrArray = &arr[i];
i++;
ptrArray++;
}
Replace ptrArray = &arr[i]; with *ptrArray = arr[i];. As it stands now, you're just overwriting the same pointer each time through the loop and never doing anything useful with it.
This is also incorrect:
string* ptrArray; //The array of string pointers
// ...
ptrToPtr = &ptrArray;
return ptrToPtr;
As soon as you return that, it becomes dangling. You're not allowed to use pointers to local (stack) variables once they're out of scope.
Firstly, I see a few problems in your setup
You don't need this for practical reasons. If you want to have the address of each element in the array, you can calculate it by incrementing the pointer to the first element (which is the array in fact). If you only do that for educational reasons forget about this
string* ptrArray = new ... Now you have an array of strings (array is semantically equaivalent to pointer to first element). But you want an array of string pointers. So you need string** ptrArray = new ... and this cascades to the rest of the function being incorrect.
You never delete the array allocated with new. This results in the memory not being free'd. You need to delete[] *strPtrs;in your last code snippet to free the memory you allocated in your method. In general it is a good idea to let the one who allocates the memory be responsibly for freeing it. I show you another idea below to handle this.
After your copy operations the pointer points past your array. Then you return a pointer to it. You applied the correct arithmetics when outputting the values in you second snippet, but I would never want to have such a pointer going around. Conventionally it should point to the first element. At least when deleting the array-pointer it has to point to the first element, otherwise you get undefined behavior e.g. deleting another array.
Lastly:
string* ptrArray; //The array of string pointers
string** ptrToPtr; //A pointer to the array of string pointers
ptrToPtr points to ptrArray, which is a local variable. It becomes invalid when leaving the function and thus it will be undefined behavior to dereference the returned pointer.
There is a common approach used by some standard libraries (e.g. snprintf from cstdio), so the caller is responsible for allocation and deallocation:
void arrayOfPtrs(string arr[], int size,/*new param*/ string** outArray)
{
string** iter = outArray; // Iterator pointer
int i = 0;
while (i < size)
{
*iter = &arr[i];
i++;
iter++;
}
}
What happens here, is that the caller gives the function a pointer to the pointers (it points to the first pointer). Note that a pointer can be used as an array with index operators etc. So it is in fact an array of pointers. You then fill it by incrementing the copied pointer so it jumps from pointer element to pointer element. Where the array actually is stored is not the problem of this function.
Use it like this:
// Variant 1: Use local variable if size is constant
string* arr[5];
arrayOfPtrs(strArr, 5, arr);
std::cout << *arr[0]; // Dereferences a pointer in arr to get the string which is actually in strArr
// Variant 2: Allocate heap memory (if you need dynamic size)
int size ...; // From somewhere
string** arr = new string[size];
arrayOfPtrs(strArr, size, arr);
std::cout << *arr[0]; // Same again
... // Do further work
delete[] arr; // Free memory
So you have to allocate memory (or use a local variable) before you call the function and then pass it to the function. In the double pointer, the first * is meant for the data type which is "pointer to string" and the second designates it as a "pointer-array".
I need to implement a function that modifies an array. The new array may be a different size. cout prints 1. I understand what's wrong with this code but I just cannot figure out what the syntax is.
//tried this..
int reduce(int *array[])
{
*array = new int[1];
(*array)[0] = 6;
return 0;
}
//also tried this..
int reduce(int array[])
{
array = new int [1];
array[0] = 6;
return 0;
}
int main()
{
int a[1] = {1};
int *p = a;
reduce(&p);
cout << a[0];
return 0;
}
Don't understand your question correctly, but this is what you may do:
void reduce(int *a, int size)
{
for (int i =0; i < size; ++i) {
*(a+i) = 6; // or whatever value to want to
}
}
Call it this way:
int main(){
int a[5] = {1, 1, 1, 1, 1};
int *p = a;
reduce(p, 5);
for (int i =0; i < 5; ++i) { cout << a[i]<<endl; }
return 0;
}
EDIT
What you are trying to do can be vaguely done this way:
int * reduce (int **b, int size) {
*b = new int[size];
for (int i =0; i < size; ++i) {
*(*b + i) = 6;
}
return *b;
}
int main(){
int a[5] = {1, 1, 1, 1, 1};
int *p = a;
p = reduce(&p, 5);
cout << p[0];
cout << p[1];
cout << p[2];
cout << p[3];
cout << p[4];
delete [] p;
return 0;
}
But it still wont change where a is pointing to.
What you are trying to do is not possible with statically defined arrays.
When you use an array like
int a[1] = {1};
you cannot change the size of the array at run time, you cannot make it point to dynamically allocated memory. You may only access and modify the elements the array. That's it.
The function reduce changes where p points to but it does not change the elements of a.
If you want to modify the contents of a, you can simply use a as an argument, and set the values.
MODIFIED:
You want to modify array a, try this :
int reduce(int **array)
{
*array = new int[1];
(*array)[0] = 6;
return 0;
}
int main()
{
int *a = new int[1];
reduce(&a);
cout << a[0];
return 0;
}
First of all, the formal parameter int* array[] actually is the same as int** array (you can think of it as a two-dimensional array). This is probably not what you want.
The answer of #everettjf will only work if you do not change the size of the array. A possible solution (that completely replaces the array) would be
#include <iostream>
void print_array(int[],int);
int* reduce(int array[]) {
// get rid of the old array
delete[] array;
// create a new one
array = new int[7]{8,4,6,19,3,56,23};
// need to return the new address, so that
// the main function is informed on the new
// address
return array;
}
int main() {
// initialize array
int *a = new int[1]{4};
print_array(a,1);
// "change" array by completely replacing it
a=reduce(a);
print_array(a,7);
return 0;
}
// simply prints out the array; no error checking!
void print_array(int array[], int length) {
std::cout << "[";
for (int i = 0; i < length ; ++i) {
std::cout << array[i] << " ";
}
std::cout << "]" << std::endl;
}
In the reduce function, the initial array is completely deleted. Afterwards, you can create a new one (I chose to just use 7 random numbers). It is important to return that pointer back to the caller (the main method). Otherwise the a pointer in the main method would point to invalid
If you are not forced (by some kind of excercise, for example) to use arrays, you should look into http://en.cppreference.com/w/cpp/container/vector
The premise of your question is invalid. It is not possible to resize an array of automatic storage duration (aka a in main()) after its definition by ANY means in standard C++.
Dynamic memory allocations in either of your reduce() functions will not cause a in main() to be resized.
reduce(&p) will calls the first version of reduce() , which will then change p (so it points at the dynamically allocated memory) but not affect a.
If main() calls reduce(a) or reduce(p) (the two are equivalent, given the initialisation int *p = a) will change neither a nor p, but instead cause a memory leak.
The underlying problem, I suspect, is that you believe - incorrectly - that pointers and arrays are the same thing. They are actually different things, but can be used in the same way in various contexts. And your code is one of the contexts in which they cannot be used interchangeably.
If you want a resizeable array, use a static container (like std::vector<int>) and - if you want a function to resize it, pass it by reference. It manages its own memory dynamically, so is able to dynamically resize itself.
I've been trying to figure this out off and on for a week now and I keep running into problems.
My objective:
Write a function that allocates memory for an integer array. The function takes as an argument an integer pointer, the size of the array, and newSize to be allocated. The function returns a pointer to the allocated buffer. When the function is first called, the size will be zero and a new array will be created. If the function is called when the array size is greater than zero, a new array will be created and the contents of the old array will be copied into the new array. Your instructor has provided arrayBuilder.cpp as starter code for this programming challenge. In addition, Lab9_1.exe is the executable for this application which you can test.
The code:
#include <iostream>
using namespace std;
int * arrayBuilder(int * arr, int size, int newSize);
void showArray(int * arr, int size);
int main()
{
int * theArray = 0;
int i;
cout << "This program demonstrates an array builder function." << endl << endl;
// create the initial array. The initial size is zero and the requested size is 5.
theArray = arrayBuilder(theArray, 0, 5);
// show the array before values are added
cout << "theArray after first call to builder: " << endl;
showArray(theArray, 5);
// add some values to the array
for(int i = 0; i < 5; i++)
{
theArray[i] = i + 100;
}
// show the array with added values
cout << endl << "Some values stored in the array: " << endl;
showArray(theArray, 5);
// expand the size of the array. size is not the original size. newSize
// must be greater than size.
theArray = arrayBuilder(theArray, 5, 10);
// show the new array with the new size
cout << endl << "The new array: " << endl;
showArray(theArray, 10);
cout << endl;
delete [] theArray; // be sure to do this a1t the end of your program!
system("pause");
return 0;
}
/*
FUNCTION: arrayBuilder
INPUTS Pointer to an array. Size of the array. If size is zero, arr can be NULL.
Size of the new array.
OUTPUTS: Returns a pointer to allocated memory. If newSize is greater than size,
an array of newSize is allocated and the old array is copied into the new
array. Memory pointed to by the old array is deleted. All new elements
are initialized to zero.
*/
int * arrayBuilder(int * arr, int size, int newSize)
{
// TODO: Your code goes here
return NULL; // default return value. No memory allocated!
}
/*
FUNCTION: showArray
INPUTS: Pointer to an array. Size of the array. If size is zero, arr can be NULL.
OUTPUTS: Prints the contents of the array to the console.
*/
void showArray(int * arr, int size)
{
cout << "arr = ";
for(int i = 0; i < size; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
My struggles: I cannot figure out how to switch "arr" and a temporary array's values.
int * arrayBuilder(int * arr, int size, int newSize)
{
// TODO: Your code goes here
int * temp = new int [newSize];
for (int i = size; i < newSize; i++)
{
*arr = *temp;
temp++;
}
return NULL; // default return value. No memory allocated!
}
another attempt while searching for answers:
int * arrayBuilder(int * arr, int size, int newSize)
{
// TODO: Your code goes here
int * temp = new int [newSize];
memcpy (temp, arr, size *sizeof(int));
// HINT: Design the function before writing it.
delete[] arr;
for (int i = size; i < newSize; i++)
{
temp[i] = i;
}
return NULL; // default return value. No memory allocated!
}
Basically my end goal is to have the answer look like this:
This program demonstrates an array builder function.
theArray after first call to the builder:
arr = 0 0 0 0 0
some values stored in the array:
arr = 100 101 102 103 104
the new array:
arr = 100 101 102 103 104 0 0 0 0 0
PROGRESS!! Its not crashing anymore :-) This is where I'm at now:
This program demonstrates an array builder function.
theArray after first call to builder:
arr = -842150451 0 0 0 0
Some values stored in the array:
arr = 100 101 102 103 104
The new array:
arr = -842150451 -842150451 -842150451 -842150451 -842150451 -842150451 -8
42150451 -842150451 -842150451 -842150451
Press any key to continue . . .
I'll keep tinkering and let everyone know if I hit a wall! Thanks again guys!
OKAY! finally got it to display properly:
This program demonstrates an array builder function.
theArray after first call to the builder:
arr = 0 0 0 0 0
some values stored in the array:
arr = 100 101 102 103 104
the new array:
arr = 100 101 102 103 104 0 0 0 0 0
This is what I did. I feel like I may have cheated in the second part when i put 0 values in for "temp". It was my understanding that i was going to take the data from the previous array and put it into the new one, and instead I just remade it. (So it will only work with this particular set of values [only 0's]). Is there a different way I can code the second part so it works universally with whatever values are thrown at it???
int * arrayBuilder(int * arr, int size, int newSize)
{
int i = size;
int * temp = new int [newSize];
// What if the size is 0?
if (size <= 0)
{
while (i < newSize)
{
temp[i] = 0;
i++;
}
}
// Assuming the size _isn't_ 0
else
{
// "a new array will be created" (good)
for (i = 0; i < newSize; i++)
{
// The contents of the "old" array (arr) will be
// copied into the "new" array (temp)
while (i < size)
{
temp[i] = arr[i];
i++;
}
while (i >= size && i < newSize)
{
temp[i] = 0;
i++;
}
// as a hint, you can address the elements in
// both arrays using the [] operator:
// arr[i]
// temp[i]
}
}
// "The function returns a pointer to the allocated buffer."
// So, NULL is wrong, what buffer did you allocate?
return temp; // default return value. No memory allocated!
}
Since you put forth some effort.
Write a function that allocates memory for an integer array.
The prototype for this function was provided for you:
int * arrayBuilder(int * arr, int size, int newSize);
The function takes as an argument an integer pointer, the size of the
array, and newSize to be allocated. The function returns a pointer to
the allocated buffer.
This says nothing about doing anything with the "old" (passed in) array, so we should assume it needs to be left alone.
When the function is first called, the size will be zero and a new
array will be created.
The above text is meaningless given the context. Feel free to tell your instructor I said so. If the size is zero, how do you know how many elements to allocate?
If the function is called when the array size is greater than zero, a
new array will be created and the contents of the old array will be
copied into the new array.
OK, now the guts of what needs to be done (you're so close)
int * arrayBuilder(int * arr, int size, int newSize)
{
// What if the size is 0?
// Assuming the size _isn't_ 0
// "a new array will be created" (good)
int * temp = new int [newSize];
for (int i = size; i < newSize; i++)
{
// The contents of the "old" array (arr) will be
// copied into the "new" array (temp)
// as a hint, you can address the elements in
// both arrays using the [] operator:
// arr[i]
// temp[i]
// something is wrong here...
*arr = *temp;
// you definitely _don't_ want to do this
temp++;
}
// "The function returns a pointer to the allocated buffer."
// So, NULL is wrong, what buffer did you allocate?
return NULL; // default return value. No memory allocated!
}
You already got the answer here:
memcpy (temp, arr, size *sizeof(int));
but you are making several other mistakes after that. Primarily, you need to return temp ; not return NULL ;
But also you don't need the loop after the delete arr[] ;
Also don't delete arr[] if size is zero.
This is horribly complex code. Programming is all about reducing complexity.
With that in mind, here’s a proper C++ solution:
std::vector<int> arr = {1, 2, 3, 4, 5};
std::vector<int> copy = arr;
That’s it. I hope this exemplifies why you should use the standard library (or other appropriate libraries) rather than re-inventing the wheel. From the code you’ve posted I am assuming that you’ve learned (or are learning) C++ from a horrible book or course. Trash that and get a proper book. C++ is complex enough as it is, no need to add needless complexity.
Just to help you realize why the first attempt didn't work:
*arr = *temp;
This is assigning a value to the old array, from the new array. That's backwards.
But it's just targeting the first value, *arr doesn't change. You increment *temp, but you also need to increment *arr. (Also, manual pointer manipulation like that horrifying and memcopy() is a lot better. But hey, this is for learning purposes, right?)
Also, think about that loop:
for (int i = size; i < newSize; i++)
That's iterating through once for each bit that newSize is bigger than size. But you're doing two things here. 1) Copying over data and 2) initializing the new data. That for loop you have is good for going over the new data, but it's not the loop you want for copying over the data you already have. That would go from zero to size, right?
And when you're done you need to return the address of the array you built.
return NULL; // default return value. No memory allocated!
That's just some dummy mock code. It's a placeholder by the teacher. It's part of the code you're supposed to change.
Per your update:
I feel like I may have cheated in the second part when i put 0 values in for "temp"
Well what else were you going to put in there? You DO copy over the old array data. Then you EXPAND the array. What goes into the new territory? Zero values as a default is perfectly valid.
Is there a different way I can code the second part so it works universally with whatever values are thrown at it???
Well yes, but you'd have to actually have something to throw at it. Your ArrayBuilder function could take in additional arguments, possibly as a variadic function, so it knows what values to put into the new fields. But your function declaration doesn't have that. All it does is make the array bigger.
Also, in your last edit you've got those two while loops that iterate through i inside of a for loop which also iterates through i. That'll work, but just so you know it's a bit... uncouth. It's the sort of thing that'll get you in trouble when things get more complicated.
You could do this instead:
for (i = 0; i < newSize; i++)
{
if(i < size)
{
temp[i] = arr[i];
}
else // if(i >= size && i < newSize) //Wait a sec, this "if" is superfluous. It's conditions are enforced the the first if and the loop condition.
{
temp[i] = 0;
}
}
You should also probably delete the comments that make it sound like someone else wrote your code for you. Because someone else did your homework for you. It's best to
Finally, THOU SHALT INDENT THY CODE!
If I have correctly understood the assignment the function should look the following way.
First of all I would substitute the function declaration
int * arrayBuilder(int * arr, int size, int newSize);
for
int * arrayBuilder( const int *arr, size_t size, size_t newSize );
Here is its definition
int * arrayBuilder( int * arr, int size, int newSize)
{
int *tmp = 0;
if ( newSize >= 0 )
{
tmp = new int[newSize] {};
int copy_size = std::min( size, newSize );
if ( copy_size > 0 ) std::copy( arr, arr + copy_size, tmp );
}
delete []arr;
return tmp;
}
Try this:
Code:
#include <iostream>
using namespace std;
int a[3] =
{
1,
2,
3
};
int b[3];
int main ()
{
cout << endl;
cout << "Array #1 elements: " << endl;
for(int i = 0; i < 3; ++i)
{
cout << a[i] << " ";
}
for(int i = 0; i < 3; ++i)
{
b[i] = a[i];
}
cout << endl << endl;
cout << "Copying Array #1 elements to Array #2..." << endl;
cout << endl;
cout << "Array #2 elements: " << endl;
for(int i = 0; i < 3; ++i)
{
cout << b[i] << " ";
}
cout << endl << endl;
return 0;
}
I have created 2 dynamic arrays in the main function. I have passed both of them to the function by reference. Then I copy data from smaller dynamic array to the larger dynamic array. I delete the smaller dynamic array. Assign the address of the larger dynamic array to the smaller dynamic array. Now ideally the arr array should have size of 10. However, when I try to print the 6th element of the array in the main, it crashes. Please have a look at the code below:
#include <iostream>
#include <string>
using namespace std;
void func(string * arr, string * brr);
int main()
{
string* arr = new string[5];
arr[0] = "hello0";
arr[1] = "hello1";
arr[2] = "hello2";
arr[3] = "hello3";
arr[4] = "hello4";
string* brr = new string[10];
func(arr, brr);
for(int i = 0; i < 6; i++)
cout << arr[i] << endl;
return 0;
}
void func(string * arr, string * brr)
{
for(int i = 0; i < 5; i++)
brr[i] = arr[i];
for(i = 0; i < 5; i++)
cout << brr[i] << endl;
delete []arr;
arr = brr;
arr[5] = "hello5";
}
This line has absolutely no effect for the caller:
arr = brr;
So after the call, arr points exactly where it used to point before - to a now invalid memory area (because you deleted it).
If this would be a C question, I would advise you to use a pointer to a pointer (string **arr). However, I feel this is nasty in a C++ program. Maybe you want to use a reference somewhere ?
Set this signature for the function
void func(string * & arr, string * & brr)
#cnicutar correctly diagnosed the problem; you'll either need to pass arr by reference (reference to the POINTER, not the array), of have fund return the new value of arr, which the caller can assign.