Click here to Skip to main content
15,884,472 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
#include <iostream.h>
#include <conio.h>
void main()

{

clrscr();
int *p1;
int n,i;
cout<<"Enter size of array ";
cin>>n;
p1=new int[n];
for(i=0;i<n;i++)
cin>>*p1++;
cout<<"output values "<<endl;
for(i=0;i<n;i++)
cout<<*p1++;

getch();
}

my program not give the correct output where is the mistake in logic
Posted
Updated 18-Apr-13 4:46am
v2
Comments
joshrduncan2012 18-Apr-13 10:44am    
You need to tell us what you expect the output to be and what you are getting. We cannot guess where it is based on what we have here right now.
ALIWAZ 18-Apr-13 10:54am    
i enter two values 1 and 2 in array but resut is 22 and 24

Reset the p1 pointer back to begin of the array before you start your output loop!
 
Share this answer
 
Comments
ALIWAZ 18-Apr-13 10:58am    
i can not please elobarate
nv3 18-Apr-13 11:16am    
By looking at your last ten questions I'd say: Do yourself a favor and read a C++ book from cover to cover (or a good website might do as well). Many of the problems you are asking help about arise just because you never got the basics down.
Sergey Alexandrovich Kryukov 18-Apr-13 11:02am    
Good catch, a 5.

I'll add a couple things. The loop variable i is declared above the loops, which is always bad. A loop variable for "for" statement should always be declared inside the "for" statement. And it's bad to give variables so short names.

—SA
nv3 18-Apr-13 11:14am    
Thanks, Sergey!
CPallini 19-Apr-13 3:25am    
I (politely :-) ) disagree on both points:
- Sometimes it is useful having a not-scoped for variable (e.g. when your loop contains a break).
- Often short variable names makes code more clean.
1. Problem with your output, you've changed p1 in your input, after your cin, p1 has pointed to the end of the array.

2. why still using
C++
iostream.h
It's too old... Try
C++
#include <iostream>
using namespace std;


3. remember to delete your pointer.
 
Share this answer
 
v5
You need to save the pointer at teh start, and restore it when you are startign the second loop:
C#
int *p1, *pStart;
int n,i;
cout<<"Enter size of array ";
cin>>n;
pStart=new int[n];
p1 = pStart;
for(i=0;i<n;i++)
   cin>>*p1++; 
cout<<"output values "<<endl;
p1 = pStart;
for(i=0;i<n;i++)
   cout<<*p1++;
delete [] (pStart);
Note that you should also get into the habit of deleting anything you allocate when you are finished with it!
 
Share this answer
 
v2
Comments
nv3 18-Apr-13 11:14am    
You make it way to easy for these guys. I had hoped he'd get that idea himself :-)
CPallini 19-Apr-13 3:20am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900