Click to See Complete Forum and Search --> : Pointers


mkan
August 13th, 2004, 06:03 AM
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:

Timir Panchal
August 13th, 2004, 06:47 AM
In the first case u r makeing Ptr to point count.

Latem
August 13th, 2004, 06:48 AM
that code shouln't even compile, and the problem is with #2 and not with #1.

try this:
#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

6
5


I dont know if you just forgot the "=" in your #1, but as you can see that works perfectly.
In your #2, the line:

int *ptr=5

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

Paul McKenzie
August 13th, 2004, 08:17 AM
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

mkan
August 13th, 2004, 08:24 AM
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

Latem
August 13th, 2004, 09:05 AM
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:

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

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

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