|
-
August 13th, 2004, 06:03 AM
#1
Pointers
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
-
August 13th, 2004, 06:47 AM
#2
In the first case u r makeing Ptr to point count.
-
August 13th, 2004, 06:48 AM
#3
that code shouln't even compile, and the problem is with #2 and not with #1.
try this:
Code:
#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;
}
that output's
I dont know if you just forgot the "=" in your #1, but as you can see that works perfectly.
In your #2, the line:
Assuming you just forgot ";", should generate a compiler error (using g++):
ptest.cpp: In function `void foo2()':
ptest.cpp:26: error: invalid conversion from `int' to `int*'
Latem
Last edited by Latem; August 13th, 2004 at 06:50 AM.
Being a pessimist is wonderful; you are either proven right, or pleasantly surprised.
-
August 13th, 2004, 08:17 AM
#4
 Originally Posted by Latem
Code:
void foo2()
{
int *ptr;
*ptr = 5;
//...
}
The behavior is undefined. The program may crash on the line *ptr =5 since ptr is uninitialized.
Regards,
Paul McKenzie
-
August 13th, 2004, 08:24 AM
#5
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
-
August 13th, 2004, 09:05 AM
#6
becuase when i say int *ptr=5
and cout<<*ptr;
output is 5 and there is no problem ,
how can this work? it doesn't even compile for me. You are trying to assign an int to *int.
You can do:
Code:
int* ptr;
int count=6;
ptr = &count;
cout << *ptr << endl;
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.
or
Code:
int* ptr = new int; // dont know how I forgot that earlier
*ptr = 5;
cout << *ptr << endl;
delete ptr;
here you allocate an integer, and then sets the value of allocated space to 6.
or
Code:
int* ptr = new int(5);
cout << *ptr << endl;
delete ptr;
here you allocate an integer abd initialize it to 6.
I am not sure if I am using the right "temenology" and words. but that's as simple as I can exmplain it.
Latem
Being a pessimist is wonderful; you are either proven right, or pleasantly surprised.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|