PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

type * variable? what does it mean?

Sorrry for this newbish question but im going through C++ unleashed currently and I keep seeing the author use declerations like
Code:
int * foo;

or
Code:
int* foo;


what do they mean? are they the same as just calling a pointer?

thanks.
yep, it's just a pointer. The 'foo' name gets used a lot for some reason. The 2 forms do the same. int* & int *
and its also the same as int *foo; ?

foo was just something i choose btw heh
If it were me writing it, I'd have done "int *foo", since "foo" is the pointer, I like to keep them together...

Doesn't matter to the compiler though. :roll:
Jadam wrote:
and its also the same as int *foo; ?

foo was just something i choose btw heh


It's also the same as

int

*

foo


;

or

int*foo;

C doesn't care about spaces or linefeeds (in most cases).

Dan East
Uh oh, another where do I put the * argument.

I do recall that Dan can stop it if it starts though, he had a really good example of why it should be int *variable instead of int* variable.

Of course as he said, C will treat it the same way.
Use whichever you like best, although I believe int* foo is in vogue these days. It only really makes a difference if you do multiple declarations on one line, which I don't do anyways:

int *foo, bar; // foo is a pointer to int, bar is an int.
And that's Dan's reason why the * should be attached to the variable name IIRC.

int* foo, bar; // foo is an int pointer, bar is an int (syntax doesn't make that obvious)
int *foo, bar; // same as before; foo is a pointer, bar is an int (syntax makes this obvious)
Speaking of an asterisk (*):

I remember during the Windows days where you need to type a password before you login which displays * on the password field.

My friend cant get into the Windows... and suddenly asked me: How many * is your password?

hehe
Thanks all!

I also have another question though, the author also uses

Code:

class dummy
{
public:
dummy(void);
~dummy(void);
char * DoThis(blah blah);
int * DoThat(blah blah);
}



now this isnt actualy code from the book, but heres my question what does char * DoThis(blah blah); do?
are you setting up a pointer towards the location of the function?

thanks.
You would be setting up a function that returns a pointer to char. You can set up pointers to functions, though. Off the top of my head: I think it would be:

char *(Dummy::*ptrname)(blah blah);

( I can't see things between code tags, so the names might not be right)
Andy wrote:
You would be setting up a function that returns a pointer to char. You can set up pointers to functions, though. Off the top of my head: I think it would be:

char *(Dummy::*ptrname)(blah blah);


Now you're really trying to confuse him. :) Pointers to class function members are something I try not to use, just because calling them seems to be more difficult than it should be.

Dan East
Yeah, I should have written more, but I'm not the greatest C++ coder around. Correct me if I make any mistakes.

1.)
Prefer (return a reference):
char &doSomething(Blah Blah)

To this (returning a pointer):
char *doSomething(Blah Blah)

If doing nothing besides pleasing the style gods, it saves you some typing when you're returning a pointer (or reference) to a custom data type and referencing a member from the returned type. If none of that made sense, don't worry.

2.) About returning pointers; really with pointers in general: You have to be super aware of the scope of your variables. A pointer is a memory address, if you give it a temporary variable like this will probably cause a crash:

int *test() {
int *returnval;
// do something with returnval
return returnval;
}

int main() {
int *testptr = test();
/* bad, because you're giving it the address of a temporary value that was released from the heap when test() exited */
*testptr = 5;
return 0;
}

The compiler should warn you about this in trivial instances like this, but pointers have inspired a great deal of hatred amongst programmers. In my experience, if a program crashes it means I did something wrong with a pointer. They offer incredibly novel solutions, but you have to be careful with them.

3.) Pointer functions are a fairly advanced C++ topic. And I don't think you need them at all. Stroustrup (author of C++) recommends that programmers use virtual functions instead of pointers to member functions where possible. I think he even calls virtual functions the "gentler cousin" of pointer-functions. If you don't know what virtual functions are -- again, don't worry.

4.) C++ can be a difficult language. I've been using it for quite a while now, and I'm not even sure I'm half way up the learning curve.

Even if you don't understand anything I said here yet, take this with you: if you ever have any problems understanding a concept, just throw something up here and someone will answer it. There's an unreal amount of skill on this board, and they seem like decent people too. So, I'm wagering that they'd take the 5 minutes to save you from 20 minutes of wrestling fruitlessly with C++ terminalogy. And that terminology does get hairy.
A little unsolicited advice for anyone that will listen...

There are times when you will have to use pointers. Some problems can only be solved, and solved well, with them.

That being said...

Many problems that you initially think pointer for can be solved without them, and most people will generally agree that avoiding pointers makes for more solid code. Well, code that's easier to get working in the first place anyway.

My own personal approach is not to treat pointers as evil, but I do treat them as a last resort. If I can do it another way, even if it's slightly less efficient, I will do so. Life is hard enough without pointers messing it up even more! :)
yeah, and you can screw up pretty bad using pointers in ways you'd never be able to with an regular variable. Especially if you're controlling hardware.

(ex.

Code:

int *foo;
int foo2;
int main(){
*foo = 10;
foo2 = foo;
}


when you're trying to get the value of *foo, you wind up getting the memory location- totally screweing up your equatoin)
Jadam wrote:
Thanks all!

I also have another question though, the author also uses

Code:

class dummy
{
public:
dummy(void);
~dummy(void);
char * DoThis(blah blah);
int * DoThat(blah blah);
}



now this isnt actualy code from the book, but heres my question what does char * DoThis(blah blah); do?
are you setting up a pointer towards the location of the function?

thanks.



No it isn't a pointer to the function, it means the return value is a pointer. For example:

char *TextName(int number)
{
if (number==1) return "one";
if (number==2) return "two";
return "unknown";
}

TextName(2) would return a pointer to the character string "two".


[Incidentally be careful that the pointer doesn't point to anything local to the function. In this case "one" and "two" are statically allocated strings, so this is okay, but that's pretty much the only situation where you do this without allocating global memory.]
Kyle Temkin wrote:
Code:

int *foo;
int foo2;
int main(){
*foo = 10;
foo2 = foo;
}


when you're trying to get the value of *foo, you wind up getting the memory location- totally screweing up your equatoin)


That's not the worst thing wrong with your example. :) foo is never assigned a value, so that memory address is not defined. So *foo=10 modifies some essentially random memory address, which will more than likely (hopefully) cause an access violation.

Dan East
Andy wrote:
Prefer (return a reference):
char &doSomething;(Blah Blah)

To this (returning a pointer):
char *doSomething(Blah Blah)


The biggest problem with that is when you aren't returning a fundamental type. So say you return a struct or a class. You have to store that "value" to work with it, which requires a copy of that struct. With a pointer you don't have any of that overhead. Also many routines returning a pointer allocate what they return, which again saves extra memory allocation / copying in the calling routine.

There's a very good reason I don't like passing by reference (ie void func(int &n;); ) - most functions do not (and should not) modify the values that were passed to them. It is too easy to shoot yourself in the foot modifying function arguments that you forgot weren't local. When you pass pointers it becomes more obvious when you are modifying them, because you have to explicitely dereference them.

To me, passing by reference was an early (and somewhat aborted) attempt to make C an easier, more type-safe language (like Pascal), and try to hide the whole concept of the pointer from the developer. Perhaps for those working with C++ using well written classes it is possible to be totally oblivious to the fact that pointers are at work. However even then with classes it is not done by reference. Personally I don't like being oblivious to the fundamental tenets and structures of the language I'm doing hardcore development in, thus pointers (and pointers to pointers, etc) are something I use very often.

It is usually all about performance, which is something in PPC development (especially gaming) is the most critical thing.

A simple contrived example - two implementations of memcpy that copy one byte at a time:

Code:

//Poor method
void memcpy(char *pTar, char *pSrc, int nLen) {
for (int i=0; i<nLen; i++)
pTar[i]=pSrc[i];
}

//Substantially better method
void memcpy(char *pTar, char *pSrc, int nLen) {
char *pEnd=pTar+nLen;

while (pTar<pEnd)
*pTar++=*pSrc++;
}


Of course copying one byte at a time is not the best method either way, but the second example requires less instructions in the inner loop.

Dan East
In the example above, foo2 would contain the address of foo - probably a mistake...

but the real problem is that (according to the code), you wrote 10 to who knows where since the pointer hasn't been pointed to anything.
Exactly what is happening when you pass by reference like this:

Code:

void func(MyClass &src) {
...
}


Is src equivalent to an automatically-dereferenced pointer, or is it something else?
Dan East wrote:Personally I don't like being oblivious to the fundamental tenets and structures of the language I'm doing hardcore development in, thus pointers (and pointers to pointers, etc) are something I use very often.


Amen.
i dunno
but if you had

Code:

int function(int &x;)
{
...
}


you would use it like

Code:

int function(int &x;)
{
int p;
p = *x * 2;
return p;
}

say if x were 4, function would return 8.

but if you want speed an easier way is
Code:

void function(int &x;)
{
*x *= 2;
}

but like dan said, that will cause hell to break loose if you screw up somewhere :-P
Code:
int function(int &x)
{
int p;
p = *x * 2;
return p;
}


Placing a * before a pointer dereferences it. Essentially, using the value at the memory address to which the pointer points. The x in this case is not a memory address.

Having the (int &x) tells the compiler that it's okay to change the value of the variable in the function. If you had (int x) it would not be okay.

If you use the & in the body of your code, it has a different meaning. It does the opposite of what a dereference does, returning a pointer to the memory address where the variable is stored.
I'll expand slightly on what Brig said. One downside of C is that the same symbol can used for different things depending on syntax. Take the asterisk. All by itself it can be used for at least 3 completely different operations:

int *i; //* indicates variable is a pointer to type int
*i=1; //Dereference a pointer
5*5; //Multiplication

The Ampersand is no exception:

void func(int &i;); //Pass by reference
int *i=&n; //Calculate address of variable n
*i=n&0xff; //binary AND

So specifying & in function declaration means pass by reference. Think of that as passing a pointer to something, but inside the function it is automatically deferenced, so you don't (can't) use * to dereference it manually (unless it is a reference to a pointer, which I do use on occasion). A simpler way to think of it is as Brig said, that you can change the value from inside the function. However it has more important lower-level meaning as well, because if the variable is not a fundamental type (ie it is a struct or class), then the whole struct does not have to be (re)copied to the stack, which would really hurt performance.

Dan East
Kyle Temkin wrote:
(ex.

Code:

int *foo;
int foo2;
int main(){
*foo = 10;
foo2 = foo;
}


when you're trying to get the value of *foo, you wind up getting the memory location- totally screweing up your equatoin)


Actually, setting *foo to 10 will just most likely give you a segfault, nothing else.

Personally, I don't see anything wrong with pointers... they're fine as long as the few basic rules are kept.
damian":14g0rotl]


Yes - the biggest problem with pointers is hanging pointers, however you can save yourself a lot of headache by just doing this:

instead of this:
char *memory;
memory=(char *)malloc(100);
...
free(memory)


just do this:
char *memory=NULL;
memory=(char *)malloc(100);
...
free(memory); memory=NULL;

or even this:
char *memory=(char *)malloc(100);
...
free(memory); memory=NULL;

This ensures you pointer is in only two states:
1) NULL, meaning that if you use it you will crash instantly, allowing you to track down code which is using the pointer before it is valid or (crucially) after it has been freed but the memory may not have been totally overwritten (the evil hanging pointers problem)

2) Non-NULL, meaning the pointer is a valid pointer to allocated memory, and it guaranteed safe to use.

I use this method on everything I write (even Java!), and I haven't looked back since!
I hate programming examples anywway. Almost as much as I hate iostream.h

I used to hate c++ for its semicolons, but I've gotten used to it (from it and PHP). If I were to program in visual basic now, I'd probably add semicolons.

char *memory=NULL;
memory=(char *)malloc(100);
...
free(memory); memory=NULL;



I prefer this:

std::vector<char> v(1000);

No hassles no worries.
mlepage wrote:

char *memory=NULL;
memory=(char *)malloc(100);
...
free(memory); memory=NULL;



I prefer this:

std::vector<char> v(1000);

No hassles no worries.


This would be much slower, initializing all 1000 elements with 0. You usually want the following:

std::vector<char> v;
v.reserve(1000);

But this doesn't allow you to access any element (the vector is still empty).

The two methods are not exact macth of the above "C" code.
Thierry you are right on both counts. Mine initializes elements to 0 (which is usually what I want anyways). Yours creates no elements. Which you want depends on your needs.

There's one more advantage to using the managed memory of the vector though. It will be freed even in the presence of an exception. The manual free will not work if an exception occurs and it is not caught.
mlepage wrote:
Thierry you are right on both counts. Mine initializes elements to 0 (which is usually what I want anyways). Yours creates no elements. Which you want depends on your needs.

There's one more advantage to using the managed memory of the vector though. It will be freed even in the presence of an exception. The manual free will not work if an exception occurs and it is not caught.


Hmmm. Religous C versus C++ battles ahoy. I have some petrol for the fire though:

Don't use C++ when C will do.
Why? Because you cannot, I repeat cannot dynamically load a C++ DLL interface on Windows.

This is something which C can do and C++ cannot.

If Winamp's plugin system was written using C++, it simply wouldn't work.

C-shaped asbestos pants activated...
If it used .NET (i.e. managed C++) it would work (use the reflection API). (COM, or COM wrappers, would be other possibilities).
<Hides>
Dave H wrote:
Don't use C++ when C will do.
Why? Because you cannot, I repeat cannot dynamically load a C++ DLL interface on Windows.


Of course you can. We do it every day with a dozen DLL at work. Where did you get this idea.
In regards to dynamically linking to a C++ dll, you can either specify the decorated function name, or if you create the DLL yourself, don't export them with the C++ calling convention.

Take a look at the dll with Dependancy Viewer to see what names you need to import.

Dan East
I agree that you can dynamically load C++.

However I also agree that in that case, a C interface is often appropriate.

But note exactly what I said: a C INTERFACE is appropriate. It can still be C++ UNDER THE HOOD. I've done that once or twice and it is the best of both worlds.
Dan East wrote:
In regards to dynamically linking to a C++ dll, you can either specify the decorated function name, or if you create the DLL yourself, don't export them with the C++ calling convention.

Take a look at the dll with Dependancy Viewer to see what names you need to import.

Dan East


Yeah but what do you about an entire class?
With C you can use GetProcAddress() or somekind of known structure. (A la Winamp)

How do you do that in C++? There is no way to tell a class to use decorated names in some other class in another DLL, and there is no support for doing that even if there was.

Do you agree with my point then - that using C++ across DLL bounaries is a bad idea?
Dave H wrote:
Yeah but what do you about an entire class?
With C you can use GetProcAddress() or somekind of known structure. (A la Winamp)


Code:

class __declspec(dllexport) MyClass
{
public:
MyClass();
// ...
};



Not as clean as I would like it to be, but definitely possible. I believe GapiDraw is using this method.
I don't know what to tell you to make you a believer, except that I've simultaneously used Java and C++ through a DLL boundary via JNI's C interface, transparently passing methods, objects, and classes. It worked on both Windows and Linux. Granted I had to write a lot of glue code to make it work, but it worked flawlessly.

Just because you believe these techniques to be impossible, hard, or not worth it, doesn't mean there aren't people out there doing it, relatively easily, because it is necessary.
mlepage wrote:
I don't know what to tell you to make you a believer, except that I've simultaneously used Java and C++ through a DLL boundary via JNI's C interface, transparently passing methods, objects, and classes. It worked on both Windows and Linux. Granted I had to write a lot of glue code to make it work, but it worked flawlessly.

Just because you believe these techniques to be impossible, hard, or not worth it, doesn't mean there aren't people out there doing it, relatively easily, because it is necessary.


Similar experience here.