473,587 Members | 2,230 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

pointer reference problem

Hi everybody,

I don't understand why I am having a problem in this code.
The problem is that my pointer *phist in main method, it is declared.
Then I send the pointer to my method, and this method creates a new object (a
Matrix) for it.

I suppose that after the new operator, my pointer is pointing to an object, so
when the method has finished, the very first pointer is still poitint to the
created method; however this is not working, I have a message as if the pointer
hasn't been initialized...

Do you have an idea?
thanks a lot for your help,

Marcelo
------
int main(){
Matrix<uchar> *mgrey;
mgrey = new Matrix<uchar>(5 ,5);

for(unsigned i=0; i < (*mgrey).getH() * (*mgrey).getW() ; i++){
*((*mgrey).val + i) = i*10;
}

Matrix<float> *phist;
Matrix<uchar> *mtest;

//here i send my pointer
mtest = method(phist, mgrey);

//my pointer has not been initialized... :(
printf("%d ",(*phist).size ());
}

Matrix<float>* method(Matrix<f loat> *ptr, Matrix<uchar> *mgrey){
..blah ...blah

ptr = new Matrix<float>(3 ,3);

blah..blah
return 0;
}
Jan 18 '06 #1
7 2039
Marcelo wrote:
Hi everybody,

I don't understand why I am having a problem in this code.
The problem is that my pointer *phist in main method, it is declared.
Then I send the pointer to my method, and this method creates a new object (a
Matrix) for it.

I suppose that after the new operator, my pointer is pointing to an object, so
when the method has finished, the very first pointer is still poitint to the
created method; however this is not working, I have a message as if the pointer
hasn't been initialized...


This may help:

http://www.parashift.com/c++-faq-lit...t.html#faq-5.8

Best regards,

Tom

Jan 18 '06 #2

"Marcelo" <ma********@yah oo.com> wrote in message
news:43******** @epflnews.epfl. ch...
Hi everybody,

I don't understand why I am having a problem in this code.
The problem is that my pointer *phist in main method, it is declared.
Then I send the pointer to my method, and this method creates a new object
(a Matrix) for it.

I suppose that after the new operator, my pointer is pointing to an
object, so when the method has finished, the very first pointer is still
poitint to the created method; however this is not working, I have a
message as if the pointer hasn't been initialized...

Do you have an idea?
thanks a lot for your help,

Marcelo
------
int main(){
Matrix<uchar> *mgrey;
mgrey = new Matrix<uchar>(5 ,5);

for(unsigned i=0; i < (*mgrey).getH() * (*mgrey).getW() ; i++){
*((*mgrey).val + i) = i*10;
}

Matrix<float> *phist;
Matrix<uchar> *mtest;

//here i send my pointer
mtest = method(phist, mgrey);

//my pointer has not been initialized... :(
printf("%d ",(*phist).size ()); }

Matrix<float>* method(Matrix<f loat> *ptr, Matrix<uchar> *mgrey){
'ptr' is a *copy* of 'phist', it's not 'phist' itself.
This function cannot modify 'phist'. When this function
returns, the object 'ptr' is destroyed.
..blah ...blah

ptr = new Matrix<float>(3 ,3);

blah..blah
return 0;
}


Arguments to functions are passed by value (this does
not change even if the argument is a pointer). The means
that the called function receives a *copy* of the argument,
it has no access to the caller's object. If you
want a function to change the caller's object, you need
to pass a pointer or (better) a reference to it.

void f(int i) // the object 'i' is an independent
// object, whose scope and lifetime
// are limited to this function's body
{
++i;
}

void g()
{
int x = 42;
cout << x; // prints 42
f(i); // this will not change 'x'
cout << x; // prints 42
}

void h(int& i) // receives argument by reference
// 'i' is not an object, but an
// alternate name for the callers'
// object.
{
++i; // increments caller's object's value
}

void k()
{
int y = 99;
cout << '\y'; // prints 99
h(y); // h() modifies 'y' (via reference)
cout << '\y'; // prints 100
}

void m(int *i) // parameter is pointer{
++(*i); // dereference pointer 'i' and modify
// what it points to
}

void n()
{
int z(25);
cout << z; // prints 25
m(&z); // pass address of 'z' (a pointer) to 'm()'
cout << z; // prints 26
}

int i; // an integer
int *i; // a pointer to an integer
int **i // a pointer to a pointer to an integer

Having said all that, I recommend you try to avoid pointers
and use references when a called function needs direct
access to its caller's arguments.

-Mike
Jan 18 '06 #3
"Marcelo" <ma********@yah oo.com> schrieb im Newsbeitrag
news:43******** @epflnews.epfl. ch...
Hi everybody,

I don't understand why I am having a problem in this code.
The problem is that my pointer *phist in main method, it is declared.
Then I send the pointer to my method, and this method creates a new object
(a Matrix) for it.


You don't "send" the pointer, you pass its (undefined) value to your
function. On entry to the function a local variable is initialized with this
(undefined) pointer value. Then you create a new object and assign its
address to the local variable. This value will be lost when the function
returns (and you'll have a memory leak). The variable which's value you
passed into the function will remain unchanged (and still undefined). Its
the same as

#include <iostream>
void foo(int bar)
{
bar = 42;
}
int main()
{
int baz;
foo(baz);
std::cout << baz << std::endl;
}

You can solve the problem if you change the first parameter of your function
to Matrix<float>** or Matrix<float>*& . Any decent book about C++ will
describe that in more detail.

HTH
Heinz
Jan 18 '06 #4
Thanks, I will try to be more specific.

Matrix : personal template class for a matrix

An external method initializes the pointer, for example:

method(matrix<f loat> *phist){
phist = new Matrix<float>(3 ,3);
}

but, when the method has finished, the pointer doesn't point to the created
object. I don't understand why. Can you help me?

thanks a lot,

Marcelo
----------

int main(){
...
Matrix<float> *phist;

//here i send my pointer
mtest = method(phist);

//my pointer has not been initialized... :(
printf("%d ",(*phist).size ());
}
Jan 18 '06 #5
Marcelo wrote:
Thanks, I will try to be more specific.

Matrix : personal template class for a matrix

An external method initializes the pointer, for example:

method(matrix<f loat> *phist){
phist = new Matrix<float>(3 ,3);
}

but, when the method has finished, the pointer doesn't point to the created
object. I don't understand why. Can you help me?

thanks a lot,

Marcelo
----------

int main(){
...
Matrix<float> *phist;

//here i send my pointer
mtest = method(phist);

//my pointer has not been initialized... :(
printf("%d ",(*phist).size ());
}


Two other people (both apparently brighter than me) have already
answered your question. It saddens me, though, that you didn't
understand my advice to you - you need to provide use with a short,
compilable example that illustrates your problem. Even after being
asked, you didn't do that.

Anyway, the other folks have already answered your question. When you
pass a non-reference argument to a function, the function creates a
local copy, which is lost upon return. Either have the function return
the value you want to use, or use references.

And if you post again, please post a short, compilable example that
illustrates your problem. I can't cut and paste what you posted to try
to compile it myself, which makes it much harder to help you.
Fortunately for you, the other respondents figured it out anyway.

Best regards,

Tom

Jan 19 '06 #6
Here is what is happening. Lets say you have two functions f(T * v) and
g( ) that calls the function f. Where T is some type.
void g()
{
T * v;
f( v );
// use v here....
delete v; // possible crash/prog mis-behavior here??
}

void f(T * p)
{
// do some thing here
p = new T; // mem leak
return;
}

in g() v is pointing to some garbage location. When you pass it to f( )
from g() a local variable p within the scope of f() is created that
also points initially to the same GARBAGE LOCATION.
------------------
v | 0xa542fca | -------------------> GARBAGE VALUE
------------------

------------------
p | 0xa882ffa | -------------------> GARBAGE VALUE
------------------

When you do new from within f() now this is the situation:
------------------
v | 0xa542fca | -------------------> GARBAGE VALUE
------------------

------------------
p | 0xa882ffa | -------------------> MEM ALLOCATED LOCATION for Type
T Constructed
------------------

once you are out of f(), p (the local variable of f() ) is destroyed.
But v inside of g() is still pointing to the same GARBAGE LOCATION !!!

So use a reference to a pointer OR a pointer to a pointer, as others
have pointed out.

- Krishna

Marcelo wrote:
Hi everybody,

I don't understand why I am having a problem in this code.
The problem is that my pointer *phist in main method, it is declared.
Then I send the pointer to my method, and this method creates a new object (a
Matrix) for it.

I suppose that after the new operator, my pointer is pointing to an object, so
when the method has finished, the very first pointer is still poitint to the
created method; however this is not working, I have a message as if the pointer
hasn't been initialized...

Do you have an idea?
thanks a lot for your help,

Marcelo
------
int main(){
Matrix<uchar> *mgrey;
mgrey = new Matrix<uchar>(5 ,5);

for(unsigned i=0; i < (*mgrey).getH() * (*mgrey).getW() ; i++){
*((*mgrey).val + i) = i*10;
}

Matrix<float> *phist;
Matrix<uchar> *mtest;

//here i send my pointer
mtest = method(phist, mgrey);

//my pointer has not been initialized... :(
printf("%d ",(*phist).size ());
}

Matrix<float>* method(Matrix<f loat> *ptr, Matrix<uchar> *mgrey){
..blah ...blah

ptr = new Matrix<float>(3 ,3);

blah..blah
return 0;
}


Jan 19 '06 #7
As a general rule, try to avoid using new where you don't need to.

Marcelo wrote:
Hi everybody,
------
int main(){
Matrix<uchar> *mgrey;
mgrey = new Matrix<uchar>(5 ,5);

for(unsigned i=0; i < (*mgrey).getH() * (*mgrey).getW() ; i++){
*((*mgrey).val + i) = i*10;
}

Matrix<float> *phist;
Matrix<uchar> *mtest;

//here i send my pointer
mtest = method(phist, mgrey);

//my pointer has not been initialized... :(
printf("%d ",(*phist).size ());
}

main could be implemented something like:

int main()
{
Matrix<uchar> mgrey( 5. 5 );
size_t height = mgrey.getH();
size_t width = mgrey.getW();
size_t dim = height * width;
for ( size_t i=0; i< dim, ++i )
{
mgrey.val[i] = i*10;
}

Matrix<float> phist;
Matrix<uchar> mtest = method( phist, mgrey );

cout << phist.size() << '\n';
}

and implement method accordingly. Note here that phist is a matrix
created with its default constructor, not a pointer to anywhere.

Not sure what you actually wanted it to be.

Jan 19 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
20515
by: JoTo | last post by:
Hi Group, sorry for my for you surely dumb question. But i'm not so familiar with this reference- and pointerstew in C++ yet. Let me explain my problem with a little Codesnippet. If i do the following: void CServerSock::OnAccept(void)
17
2583
by: Divick | last post by:
Hi, I am designing an API and the problem that I have is more of a design issue. In my API say I have a class A and B, as shown below class A{ public: void doSomethingWithB( B * b) { //do something with b //possibly store in a list
12
5377
by: Mike | last post by:
Consider the following code: """ struct person { char *name; int age; }; typedef struct person* StructType;
51
4426
by: Kuku | last post by:
What is the difference between a reference and a pointer?
8
2392
by: toton | last post by:
HI, One more small doubt from today's mail. I have certain function which returns a pointer (sometimes a const pointer from a const member function). And certain member function needs reference (or better a const reference). for eg, const PointRange* points = cc.points(ptAligned);
2
2830
by: toton | last post by:
Hi, This is continuation of topic pointer & reference doubt. http://groups.google.com/group/comp.lang.c++/browse_thread/thread/df84ce6b9af561f9/76304d7d77f6ccca?lnk=raot#76304d7d77f6ccca But I think it is better to have a new topic rather than continuing on old one. As now I am sure pointer to reference and reference to pointer are freely...
33
5037
by: Ney André de Mello Zunino | last post by:
Hello. I have written a simple reference-counting smart pointer class template called RefCountPtr<T>. It works in conjunction with another class, ReferenceCountable, which is responsible for the actual counting. Here is the latter's definition: // --- Begin ReferenceCountable.h ---------- class ReferenceCountable
29
3636
by: shuisheng | last post by:
Dear All, The problem of choosing pointer or reference is always confusing me. Would you please give me some suggestion on it. I appreciate your kind help. For example, I'd like to convert a string to a integer number. bool Convert(const string& str, int* pData); bool Convert(const string& str, int& data);
6
2507
by: worlman385 | last post by:
For pointer and non-pointer initialization of an object like MyCar mycar; MyCar* mycar = new MyCar(); I heard from other people saying if object i create must live outside scape, then I use pointer version, else if only use object for a limited scope, then use non-pointer version. Does limited scope means the object is only used in...
0
7915
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8339
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
6619
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5392
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3840
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3872
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2347
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1452
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1185
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.