I have a silly doubt
1) int *ptr
int count=6;
ptr &count;
cout<<*ptr<<endl;
2) int *ptr=5
cout<<*ptr<<endl;
In both the cases the value of *ptr is 5. Then why do we always do it as in the first case :eek:
Printable View
I have a silly doubt
1) int *ptr
int count=6;
ptr &count;
cout<<*ptr<<endl;
2) int *ptr=5
cout<<*ptr<<endl;
In both the cases the value of *ptr is 5. Then why do we always do it as in the first case :eek:
In the first case u r makeing Ptr to point count.
that code shouln't even compile, and the problem is with #2 and not with #1.
try this:
that output'sCode:#include <iostream>
using namespace std;
void foo1();
void foo2();
int main()
{
foo1();
foo2();
return 0;
}
void foo1()
{
int *ptr;
int count=6;
ptr = &count;
cout << *ptr << endl;
}
void foo2()
{
int *ptr;
*ptr = 5;
cout << *ptr << endl;
}
I dont know if you just forgot the "=" in your #1, but as you can see that works perfectly.Quote:
6
5
In your #2, the line:
Assuming you just forgot ";", should generate a compiler error (using g++):Code:int *ptr=5
LatemQuote:
ptest.cpp: In function `void foo2()':
ptest.cpp:26: error: invalid conversion from `int' to `int*'
The behavior is undefined. The program may crash on the line *ptr =5 since ptr is uninitialized.Quote:
Originally Posted by Latem
Regards,
Paul McKenzie
hi,
Yes i have forgotten "="
anyway my doubt is , is it must than i have to say
ptr= &count
becuase when i say int *ptr=5
and cout<<*ptr;
output is 5 and there is no problem , then why are we giveing the line
ptr= &count
how can this work? it doesn't even compile for me. You are trying to assign an int to *int.Quote:
becuase when i say int *ptr=5
and cout<<*ptr;
output is 5 and there is no problem ,
You can do:
Here a pointer to integer (ptr) is declared. integer count is assigned a value of 6. Then ptr is made to point to the address of count.Code:int* ptr;
int count=6;
ptr = &count;
cout << *ptr << endl;
or
here you allocate an integer, and then sets the value of allocated space to 6.Code:int* ptr = new int; // dont know how I forgot that earlier
*ptr = 5;
cout << *ptr << endl;
delete ptr;
or
here you allocate an integer abd initialize it to 6.Code:int* ptr = new int(5);
cout << *ptr << endl;
delete ptr;
I am not sure if I am using the right "temenology" and words. but that's as simple as I can exmplain it.
Latem