Aoa,
Hello All,

i am having problem in this question

Write a program that takes integer input from the user and store into the array dynamically allocated each time a new element is added. Your program should prompt user to take integers until he enters -1, which means end of input. After taking all the numbers print them in the reverse order as entered by the user.

the code which i have written is attached along.
it is printing junk values.
need help :)

regards

code goes here

#include <iostream>
using namespace std;

void question1();

int main()
{
	question1();
}
void question1()
{
	int i=0;
	int* ptr=nullptr;
	int* temp=nullptr;

	bool boolean=true;
	while(boolean!=false)
	{
		cout << "Enter number: " << endl;
		int* ptr=new int[i+1];
		cin >> ptr[i];
		if(ptr[i]!=-1)
		{
			temp = new int[i+2];
			
				for(int k=0; k<i; k++)
				{temp[k]=ptr[k];}
				i++;
		}
		else
		{
			for(int j=i-1; j>=0; j--)
			{
				cout << temp[j] << " " ;
			}
			boolean = false;
		}
	}
	delete[]ptr;
	delete[]temp;
}

You are changing ptr BEFORE you copy the contents of the array, so when you copy ptr, you're copying garbage values.

You're also causing memory leaks repeatedly; you delete each array once, at the end, but you call new many many times in your looping.

Edited 4 Years Ago by Moschops: n/a

The code continually allocates new memory to ptr, which leaks away the previous memory and loses any previously assigned numbers. Rather than outline all of the possible cases and explain why they're necessary, I'll just give you a function to study:

bool ResizeArray(int*& a, unsigned old_size = 0, unsigned new_size = 0)
{
    bool rc = false;
    
    if (new_size != 0 && old_size != new_size)
    {
        if (!a)
        {
            // Allocate a new array of non-zero size
            //
            try {
                a = new int[new_size];
                rc = true;
            }
            catch (...)
            {
                // No cleanup, just converting an exception into a return code
            }
        }
        else
        {
            // The new size is different on an existing array; try to resize
            //
            unsigned n = new_size > old_size ? old_size : new_size;
            int* temp = nullptr;
            
            try
            {
                temp = new int[new_size]; // Might throw
                
                for (int i = 0; i < n; i++)
                {
                    temp[i] = a[i]; // Might throw
                }
                
                delete[] a;
                a = temp;
                rc = true;
            }
            catch (...)
            {
                if (temp)
                {
                    delete[] temp;
                }
            }
        }
    }
    
    return rc;
}

Don't copy it mindlessly, try to understand what's being done, in what order, and why. There are three steps:

  1. Allocate a temporary array.
  2. Copy existing elements into the temporary array.
  3. Replace the original array with the temporary array.

But the logic varies depending on things like if the original array hasn't yet been allocated any memory and is a null pointer, and the relationship between the old size and the new size.

Edited 4 Years Ago by deceptikon: n/a

Here, you have declared a variable called ptr

void question1()
{
int i=0;
int* ptr=nullptr;

Here you are declaring a completely different variable, which also happens to be called ptr and hides the variable you'd previously declared by the same name.

while(boolean!=false)
	{
		cout << "Enter number: " << endl;
		int* ptr=new int[i+1];

Since this new ptr variable is declared inside your loop, it is destroyed at the end of your loop, and the new int[] memory which you'd allocated is being leaked, since there are no other references to it in your program.

I'd suggest renaming one of your 'ptr' variables, and being careful to ensure that the memory you're allocating is properly tracked, and also deleted when you no longer needed. (Note, memory allocated using new[] needs to be cleaned up with delete[] - don't omit the subscript [] operator)


Alternatively, a smarter way to do this (without new/delete) would be to avoid yucky stuff like pointers and new/delete, then to replace it with a vector (which is a resizable "C++ array")

#include <vector>
// ... etc.
vector<int> temp;
bool boolean=true;
while(boolean!=false)
{
    cout << "Enter number: " << endl;
    int n;
    cin >> n;
    if(n!=-1)
    {
        temp.push_back(n);
    }
    else
    {
        for(int j = temp.size() -1 ; j>=0; j--)
        {
            cout << temp[j] << " " ;
        }
        boolean = false;
    }
}

Edited 4 Years Ago by Bench: n/a

thanks all but still i cannot figure out what to do
and unfortunately i have to use only dynamic arrays so i cannot use vectors and i havent also studied them yet.

You are making it so hard! The instructions are:

Write a program that takes integer input from the user and store into the array dynamically allocated each time a new element is added.

Note the wording: "store into the array dynamically allocated ".
Allocate a buffer of sufficient size -- once.
There is nothing in the instructions that says allocate a new buffer for each and every integer.

I usually use tools for search memory leaks - deleaker (Windows) or valgrind (Ubuntu):-/
I'm stupid and lazy :icon_cool:

This question has already been answered. Start a new discussion instead.