954,219 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

*Pointer program problem.

#include
using namespace std;

int main()
{
int age;

for (int i=0;i<5;i++)
{
cout << "Enter :";
cin >> age;
}

int *sum=&age;


for ( i=0;i<5;i++)
{
cout <<*(sum+i) << endl;
}
return 0;
}

here is one of my program that i wrote.
i do not know whats the problem with it.
it seems can't display back the values that i've entered in.
can sir/miss help me to correct my mistake(s).
Thank you!

koh
Junior Poster in Training
73 posts since Jul 2004
Reputation Points: 11
Solved Threads: 0
 

Try:

cout <<(*sum+i) << endl;

You want the asterisk in front of the pointer you want to dereference, not in front of the expression. What you were saying was:

"print out the contents of the int pointer at location (sum + i)" which is the same as saying

cout << sum[i] << endl;

Chainsaw
Posting Pro in Training
436 posts since Jun 2004
Reputation Points: 36
Solved Threads: 11
 
int age;


You haveage declared as a single int, but later try to operate on it as if it were an array of ints, which it is not.

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

An array is declared:
datatype array_name[int_size];

Eg. int vals[10];

int *p = vals;

Then p[0] = vals[0] and p[1] = vals[1] and so on.
Also you can access the vals by *(p+i) instead of the [], and the expression is read as the value at the address of p+i.

An array var is also a pointer so you dont need a & in front of it when you assign it to another pointer.But if you want to just point to a single int for example:

int *p = &val; //means p = address of val

and you can access the value a the address pointed to by p usinf another_int = *p ;

---Helps???

FireNet
Posting Whiz in Training
258 posts since May 2004
Reputation Points: 108
Solved Threads: 7
 

thank you everyone ;)

koh
Junior Poster in Training
73 posts since Jul 2004
Reputation Points: 11
Solved Threads: 0
 
#include <iostream>
using namespace std;

int main()
{
int age;

for (int i=0;i<5;i++)
{
cout << "Enter :";
cin >> age;
}

int sum=age;

for (int  i=0;i<5;i++)
{
cout <<sum+i<< endl;
}

int name;
cin>>name;
}


Salam friends.this is me faizan ahmed, this program just prints the values which u entered before..as one of my friend was asking to print those entered values so i found this way ;)

ZON
Newbie Poster
2 posts since Apr 2010
Reputation Points: 9
Solved Threads: 0
 

6years too late and ignoring rules.

Thread closed

peter_budo
Code tags enforcer
Moderator
15,436 posts since Dec 2004
Reputation Points: 2,806
Solved Threads: 901
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You