Make array in cpp - c++

I am trying to make a new array in my project
the code is:
#include <iostream>
using namespace std;
void makeArray( int *& arrayPtr, int size );
int main( )
{
int * arrPtr;
int size =10;
makeArray( arrPtr, size );
for(int j=0;j<size;j++)
{
cout<<arrPtr[j]<<endl;
}
}
void makeArray( int *& arrayPtr, int size )
{
int arr[size-1];
for(int i=0;i<size;i++)
{
arr[i]=0;
}
*&arrayPtr=*&arr;
}
According to the requirements i need to use the above "makeArray" method inorder to make the array.
When i run the code the output is garbage values not zero.....
any help will be appreciated
thank you

The way you are creating the array is on the stack, which means that it will not exist after the makeArray function finishes.
You will need to allocate the array on the heap.
So:
int arr[size-1];
should be:
int *arr = new int[size-1];
Also, I think you mean to do this in makeArray():
arrayPtr = arr;
Instead of:
*&arrayPtr=*&arr;
Which compiles but is more complex and is functionally the same thing in this context.
But you may prefer just returning an int* instead of taking a reference to the pointer.
Then when you are done using the array in main(), and set it to NULL just in case you accidentally use it again, like this:
for(int j=0;j<size;j++)
{
cout<<arrPtr[j]<<endl;
}
delete [] arrPtr;
arrPtr = NULL;

Why are you declaring a parameter as 'int *& arrayPtr'? Do you just need a pointer to an array? You should use 'int *arrayPtr' instead.
To answer your question, the problem is that you are declaring an array in the function makeArray's stack. Upon the completion of a function, that function's stack is destroyed, so you're passing the address of junk data. To avoid this, use dynamic memory allocation instead.
EDIT: Also, you should use memset instead of a for loop to zero an array. It's much faster.

The "arr" which you allocate in "makeArray()" is local. and when the functione is over the array is release. When you back to main you get garbage.
What you want to do, is to use the "new" operator to allocate this new array to be used in all program, unless you will free this memory by "delete".
so you can set your makeArray() to:
int* makeArray(int size )
{
int *arr = new[size];
for(int i=0;i<size;i++)
{
arr[i]=0;
}
return arr;
}
the in you main you need to initialize your arry by:
int * arrPtr = makeArray(10);
just don't forget to release this memory after you finsh:
delete[] arrPtr ;

Related

C++ printing array results

I was able to fix some of the errors. Now I am just getting 3.
1. control reaches end of non-void function at } before the
void displayIntegerArray(int *arrayPtr,int arraySize) function.
2. expected expression at delete[];.
3. expected expression at return 0;.
#include <iostream>
#include <iomanip>
using namespace std;
// Function prototypes
void populateIntegerArray(int *arrayPtr, int arraySize);
void displayIntegerArray(int *arrayPtr, int arraySize);
void findMaximumInteger(int *arrayPtr, int arraySize);
//method to populate array
void populateIntegerArray(int *arrayPtr,int arraySize)
{
for(int i=0;i<arraySize;i++)
{
cout<<"Enter value for array element:"<<i<<":";
cin>>arrayPtr[i]; //reading value
}
}
void findMaximumInteger(int *arrayPtr,int arraySize)
{
int maximum = arrayPtr[0];
{
for(int i=0;i<arraySize;i++)
{
if(maximum<arrayPtr[i])maximum=arrayPtr[i];
}
cout<<"Maximum integer in array is: "<<maximum<<endl;
}
}
void displayIntegerArray(int *arrayPtr,int arraySize)
{
for(int i=0;i<arraySize;i++)
{
cout<<&arrayPtr[i]<<": arrayPtr["<<i<<"] = "<<setw(15)<<arrayPtr[i]<<endl;
}
}
int main()
{
int arraySize;
// Read array size
cout<<"Enter desired array size:";
cin>>arraySize;
// Print array
cout<<"arrayPtr = "<<arraySize<<endl;
populateIntegerArray( arrayPtr, arraySize);
displayIntegerArray(arrayPtr, arraySize);
findMaximumInteger( arrayPtr, arraySize);
cout<<"DELETING array at arrayPtr = "<<arrayPtr<<endl;
delete[];
return 0;
}
In main function:
There is undeclared variable; arrayPtr.
So you have to declare it and allocate memory for it dynamically.
int* arrPtr = new int[arraySize];
You also have to provide the delete [] operator the arrayPtr to free the memory allocated.
Finally main function will be like that:
int main()
{
int arraySize;
// Read array size
cout<<"Enter desired array size:";
cin>>arraySize;
int *arrayPtr=new int[arraySize];
// Print array
cout<<"arrayPtr = "<<arraySize<<endl;
populateIntegerArray( arrayPtr, arraySize);
displayIntegerArray(arrayPtr, arraySize);
findMaximumInteger( arrayPtr, arraySize);
cout<<"DELETING array at arrayPtr = "<<arrayPtr<<endl;
delete[] arrayPtr;
return 0;
}
So there are a couple of things that ain't quite right with your program my dude, but they mainly stem from you not creating a arrayPtr in main. If you don't create something to point to a chunk of memory then your program wont know where the array is.
https://www.cplusplus.com/doc/tutorial/pointers/
The next problem is that, because you never created the pointer to the memory, you also forgot to create the space for the memory. If the array was the same size every time your program ran and was reasonably small then you could just allocate the space on the stack. However you don't so you need to allocate the memory dynamically. This means that you need to ask your operating system for the memory and get back its location. This can be done with the new[] operator. Then when you are done using the memory you tell the program to de-allocate it with the delete[] operator. (If you don't then memory will keep being marked as used despite your program ending. This is called a memory leak.)
https://www.cplusplus.com/doc/tutorial/dynamic/
Next you aren't actually displaying the location of the array. You want to print the new arrayPtr variable to see the location.
Lastly your post is a bit hard to work with. The formatting is a bit inconstant and that makes it significantly harder to read. Luckily your program was simple enough that it isn't too time consuming to read through and figure out what is going wrong. However, as your programs get more complex and larger, many people won't be willing to look through your whole program and find your bugs for you. Try to narrow down where you think the error is coming from and post: some context, the relevant chunk of code, and the exact error messages.

How could I allocate 1D array by using pointer to pointer (int **)

What is the difference in
void AllocateArray(int **arr,int size)
and:
void AllocateArray(int *arr,int size)
I have to allocate only 1D array by using both, and what is difference?
I suppose the usage should be:
int* arr;
AllocateArray(&arr, 10);
// array has been allocated, use arr[0]...arr[9].
// ...
delete[] arr; // don't forget this
According to the function's name, it might allocate the memory for the array. Such as:
void AllocateArray(int **arr,int size) {
*arr = new int[size];
}
The second AllocateArray's parameter(i.e. int *arr) is passed by value, that means even the memory is allocated inside the function, it has nothing to do with the outside variable.
How could i allocate 1D array by using pointer to pointer (int **)
int **p=new int*[1];
*p=new int[20];
But why? It is too bad to do it like this
What is the difference
void AllocateArray(int **arr,int size) can change the address of the array not just the content of it. In other words:
int *p;
AllocateArray(&p,5);
Will be able to change where p is pointing to.
void AllocateArray(int *arr,int size) can only change the content of the array. In other words:
int *p;
AllocateArray(p,5);
Will be change the content of p without changing where it is pointing to.
P.S. I know that pointer != array but since it is an elementary question I did not need to dig into such detail for the OP.
Final Note:
Please use std::vector instead all of these pointers. You will be in peace and feel loved.

Array initialization functions

I was playing around with C++ and I stumbled upon this problem. I'm trying to initialize an array pointer on the heap, and it works inside the initialize(), where it outputs 69, but in the main(), it crashes with the error EXC_BAD_ACCESS.
#include <iostream>
void initialize(int* array, int size) {
array = new int[size];
// Testing
array[2] = 69;
std::cout << array[2] << std::endl; // Works fine
}
int main() {
int size = 3;
int* array;
// Initializing
initialize(array, size);
// Testing
std::cout << array[2] << std::endl; // Crash, EXC_BAD_ACCESS
// Cleanup
delete[] array;
array = nullptr;
return EXIT_SUCCESS;
}
Please help me understand the problem with this.
Yes, I know I should use std::vector but I want to understand why this doesn't work :)
When you pass array to the function, a copy of that pointer is made. When you assign new int[size]; to array, you assign it actually to the argument, which is the copy I was talking about. To really modify the array defined in main, use references. Change the definition of the function to
void initialize(int*& array, int size)
or return the pointer like1
int* initialize(int size)
and try it again.
I recommend the second method due to its higher expressiveness: something like
initialize(array, 3);
does not make clear if array is modified or not. OTOH,
int* array = initialize(3);
does.
1 as noted by #Jack in the comments to this answer
The reason why the program fails is because you want the memory to be allocated outside the initialize function and the function to operate on that memory.
Simply remove the new statement from your function so that it looks like this...
void initialize(int* array, int size) {
for (int i = 0; i < size; i++) {
cout << array[i] << " ";
}
}
... then, do your allocation in main and just before the function call...
int size = 3;
int* array = new int [size];
initialize(array, size);
Pass the address of the pointer to avoid the error message

Heap Corruption Detected in Dynamic Array c++?

I was learning how to use the delete operator for dynamic arrays and i ran into some really strange problem. I tried two approach to write the same code - one worked but the other dint work. So, here is the code i tried
Method 1:-
#include <iostream>
using namespace std;
int main()
{
int *p = new int(2);
for(int i =0; i<2;i++)
{
cin>>p[i];
}
for(int i=0; i<2;i++)
{
cout<<p[i];
}
delete[] p;
system("pause");
}
//Error message - Heap Corruption detected. Can someone please explain me the reason of the error?
Method 2:- Using TypeDef
#include <iostream>
using namespace std;
typedef int arr[2];
int main()
{
int *p = new arr;
for(int i =0; i<2;i++)
{
cin>>p[i];
}
for(int i=0; i<2;i++)
{
cout<<p[i];
}
delete[] p;
system("pause");
}
//The above method works perfectly with no error. I am totally confused!!
First case: you are only creating one int and assigning it the value of 2.
Then you treat it as an array with two elements. That's undefined behaviour. You need to use new int[2]. Your delete[] syntax is correct.
Your second example is far too obfuscated.
You're calling the constructor of one int with the value of 2 not allocating two ints.
Use square brackets instead.
int *p = new int[ 2 ];
new int(2) allocates one int that has the value 2.
new int[2] allocates an array of two ints, with indeterminate values.
in your first example you have:
int *p = new int(2);
which is initializing 1 pointer to the value of 2 rather than in your second example when you have a
new int[2];
where you're actually making 2 pointers.

C++ Class pointer is not saving anything.

The following is a small scale example of the problem I am facing. In the example below I use int pointers but in my own code I am really using a pointer to another class (a node class).
The problem appears to be that I am using a call by value pointer (if there is such a thing). I don't know, I thought pointers were by reference. I do need to be able to pass multiple pointers to the method and I do not really want to write a specific method for each pointer. When I run the code, of course, I get some kind of error because it is trying to access a pointer that has not been allocated.
I do not understand why it would not initialize the correct pointer if I pass the specific pointer I want.
Any help would be greatly appreciated.
#include <iostream>
using namespace std;
class Test {
private:
int *p1;
int *p2;
int sizeP1;
int sizeP2;
public:
int* getIntPointer() {return p1;}
void initializeP1(int *ip,int n){
sizeP1=n;
ip=new int[n];
for(int i=0;i<n;i++)
p1[i]=i;
}
void printP1() {
for(int i=0;i<sizeP1;i++)
cout<<p1[i]<<" ";
}
};
int main() {
Test t;
t.initializeP1(t.getIntPointer(),10);
t.printP1(); //this fails.. but why? How can I fix it?
return 0;
}
The problem is that you initialize ip and you fill p1
void initializeP1(int **ip,int n){
sizeP1=n;
*ip=new int[n];
for(int i=0;i<n;i++)
*ip[i]=i;
}
//call with p1
initializeP1(&p1, 10); // pass pointer to pointer so you can get return value.
The problem is that your function allocates memory to the copy of the pointer that is the argument - this copy is lost at function exit. Pass the pointer by reference instead by changing the function signature
void initializeP1(int* &ip,int n){
^
This way the allocated memory is still accessible and your pointer will point to it
Would it not simply be easier to change your initializeP1 function to something like:
int * initializeP1(int n)
{
sizeP1 = n;
p1 = new int[n];
for(int i = 0; i < n; ++i)
p1[i] = i;
return ip;
}
There are still problems with this however, such as the fact that you can call it repeatedly and cause big memory leaks.
It might be better to use a proper constructor for your class that does what initializeP1 did, like such:
Test(int n)
{
sizeP1 = n;
p1 = new int[n];
for(int i = 0; i < n; ++i)
p1[i] = i;
return ip;
}
Pointers are not passed by reference, no. Pointers are value types. You'd want to use a reference if you absolutely had to make it look like this, but it's an abuse of syntax and you should do it a different way instead.
The call to t.getIntPointer() returns a pointer that is not initialised to something sensible.
The call to initializeP1() is newing an array of ints.
But be careful, this allocated block of memory will not be freed until you tell it so by writing "delete [] p1;".