C++ Passing a struct to a function

This topic is 2543 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I know how to pass a variable to a function through a pointer parameter to change its value. See code:
void Inc(int *var)
{
*var=*var+1;
}
I need to be able to pass struct to a function in a similar way so that its contents can be changed. Would it be something like this?
(I know it doesn't work, just shows the concept.)
#include "stdafx.h"
#include <iostream>
#include "Stdio.h"

struct test {
int num;
};

void Inc(test *var);

int _tmain(int argc, _TCHAR* argv[])
{
test i;
i.num=5;

Inc(&i);

//Should print "6"
printf("%d\n",i);
system("pause");

return 0;
}

void Inc(test *var)
{
*var.num=*var.num+1;
}

By the way what are the tags to make code in a code box?

Share on other sites
Instead of using a pointer in the function parameters try a reference & like this

void Inc(Test& Var)
{
Var.num += 1;
}

should increment to 6 for you.

Share on other sites
The problem you're having is one of syntax. You need to dereference "var" before using the member access operator, like so:
void Inc(test *var){    (*var).num = (*var).num + 1;}

Better, use the arrow operator, which is shorthand:
void Inc(test *var){    var->num = var->num + 1;}

Full program example, fixing other errors:
#include <iostream>#include <cstdio>struct test{     int num;};void Inc(test *var);int main(int argc, const char* argv[]){    test i;    i.num=5;    Inc(&i);    // Should print "6"    printf("%d\n",i.num);}void Inc(test *var){    var->num = var->num + 1;}

Better still, use references as wicked357 suggested.

Share on other sites
Thanks, worked great. But is one method better than the other?

Share on other sites
Use references were ever possible, it allows the compiler to do its job better of optimizing. The reason is that a reference cannot change, but a pointer can change. For example

void func1(int& k){
k+=1;// easy enough, add 1 onto k
}
void func2(int* k){
k+=1;// increment the address of k to point 1 byte after where it was previously pointing ..
*k+=1;// now, what ever k is pointing to is changed....whats there? I dont know, maybe the compiler doesn't either
}

now, in func1, k is actually the int passed to the function, and in func2, i changed the address of what k was pointing to and the compiler may not know what is at that address, so it will leave this until run-time. These are extremely simple examples that will show you how if something is known at compile time, the compiler should do its job and figure it out, but if it is not known until run-time, then the compiler cannot do its job.

So, use references were ever possible..... points only where its absolutely needed.

Share on other sites
Okay, I get it. Thanks for the help.

Share on other sites
Quote:
 Original post by smasherprogUse references were ever possible, it allows the compiler to do its job better of optimizing. The reason is that a reference cannot change, but a pointer can change.
Much more importantly, a reference can never be null, and a reference can never point to invalid memory*. When you use a pointer you need to account for the possibility that you are passed a null or invalid pointer, so references both reduce effort and increase the robustness of your code.

*This is not entirely true: it is possible to construct null/invalid references, but not without some very obvious intent. It isn't going to happen accidentally.

Share on other sites
I have a question, I am sorry if I should have made my own topic this one made me think of the question. What would happen if you were to do something along the lines of:

int inc(int& Val){
return (Val++);
}

int main(){
inc(7);
return 0;
}

Share on other sites
You would get a compiler error. You can't bind a non-const reference to an rvalue.

Share on other sites
Quote:
 Original post by 4th_dimentionI have a question, I am sorry if I should have made my own topic this one made me think of the question. What would happen if you were to do something along the lines of:int inc(int& Val){return (Val++);}int main(){inc(7);return 0;}

Suggestion: just do it... Type it, compile it (if you can, this you cannot) and, after that, debug it step by step, using the watch to see all the values in question. You will learn some new things from it.

Be brave :)

Share on other sites
Quote:
 Suggestion: just do it... Type it, compile it (if you can, this you cannot) and, after that, debug it step by step, using the watch to see all the values in question. You will learn some new things from it.

Unfortunately in C++, a compiling or even successfully running program does not mean that the code is correct. There are cases where you invoke undefined behaviour and on most implementations the program will appear to continue to work. The problem is when you port to an alternative implementation or even just modify the surrounding code, strange and subtle bugs can appear.

In this case, were the type a structure rather than an integer then MSVC would accept and compile the code passing a temporary to a non-const reference.

Yes, debugging (or examining the assembly of) a particular implementation is enlightening, but it cannot be taken as a reference for the standard, particularly when undefined behaviour is likely.

Share on other sites

you're talking generics, I'm talking specifics: he was near a pc, he was wondering "what would happen if" , he concoted some code, he posted it on a forum and then he waited... In the meanwhile he could just as well figure it out by just trying it. I didn't say it is better than reading some specs or whatnot... Think before you post.

As for "port to an alternative implementation" and "just modify the surrounding code" ending up with "strange and subtle bugs can appear", if you know what you're doing, you should take care and not introduce "subtle bugs"... I could tell you stories from the 12 years I've been toying with programming. Or of the 5 years I've been doing it while working on 4 commercially available games (1 X360, 2 PS3 and 1 PC title). I could tell you all sorts of issues I had while moving from one (microsoft) compiller to the one Sony uses... But that would be besides the point of this thread.
He's just not that advanced yet, therefore it's nothing wrong to try, Of course, he should read the standard, understand it and then all his questions will be answered. But, given the "not perfect" nature of the situation, I was just encouraging him to try before crying for help, as I always favor the situations like "well, I tried this and that and this is what happened, anyone having an idea why" as opposed to "what would happen if " and then wait for someone else to do all the figuring out and present a cut and dry answer...

Share on other sites
Quote:
 Original post by LordJulianRead again what he askes, what I answered and what you argued agains...you're talking generics, I'm talking specifics

And the OP (EDIT: well, what should've been the OP as this would've been better off in a new thread — no biggie) is likely talking generics and just happened to give a specific example, since these things can help clarify what we're all talking about.

More importantly, it also looks like your advice is also generic: "Try it, see what happens." It's well worth commenting on the problems with this in C++ even if you didn't mean for it to be a generic statement, given how easy it would be to misinterpret you.

There are plenty of ways to introduce subtle bugs without knowing it, as this quiz frequently demonstrates, and a beginner asking questions... especially in the confusing realm of pointers and references, should not be discouraged.

Quote:
 Think before you post.

Yes, yes you should.

[Edited by - Washu on December 29, 2010 12:35:19 AM]

Share on other sites
Simple quiz is simple.

Sorry, had to do it :p

Share on other sites
Quote:
 Original post by LordJulianSimple quiz is simple.Sorry, had to do it :p

Yes, such a simple quiz. Funny though how most developers manage to fail it, even professional ones.

Share on other sites
Quote:
Original post by Washu
Quote:
 Original post by LordJulianSimple quiz is simple.Sorry, had to do it :p

Yes, such a simple quiz. Funny though how most developers manage to fail it, even professional ones.

Either they are not focused on the test or they are not professionals... Being a programmer is more than 60% about the subtle stuff... Actually, being a professional is more than 60% about the subtle stuff

Share on other sites

This topic is 2543 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Create an account

Register a new account

• Forum Statistics

• Total Topics
628738
• Total Posts
2984464

• 12
• 25
• 11
• 10
• 16