473,652 Members | 3,173 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Pass-by-reference to nested function?

S.
Hi all,

I have the requirement that I must pass-by-reference to my function
addStudent() and getAge() functions where my getAge() function is
within the addStudent() function. I am able to pass-by-reference to
the first function, addStudent() but then I am confused as to how I am
suppose to pass the pointer of 'student' from within the addStudent()
function to the getAge() function that is nested within the
addStudent() function.

My code below does not compile correctly with the inclusion of the
getAge() function and I receive the following compile warning:
"test2.c", line 30: warning: left operand of "->" must be pointer
to struct/union
where line 30 is:
scanf("%d", student->age);

I understand this is not the "simplest" way to achieve the inputs for
the student's name and age but it is my requirement to have the nested
functions and to pass variables by reference. Thanks for your help in
advance.

S.

#include <stdio.h>
#define NAME_SIZE 20
#define CLASS_SIZE 10

typedef struct {
char name[20];
int age;
} Student;

void addStudent(Stud ent *student);
void getAge(Student **student);

void main() {
Student students[CLASS_SIZE];
addStudent(&stu dents[3]);
return;
}

/* Pass-by-reference */
void addStudent(Stud ent *student) {
printf("\nStude nt name: ");
scanf("%s", student->name);
printf("\nStude nt age: ");
getAge(&student );
return;
}

/* Pass-by-reference */
void getAge(Student **student) {
scanf("%d", student->age);
return;
}
Jun 27 '08 #1
4 6678
In article <02************ *************** *******@i36g200 0prf.googlegrou ps.com>,
S. <si********@gma il.comwrote:
>I have the requirement that I must pass-by-reference to my function
addStudent() and getAge() functions where my getAge() function is
within the addStudent() function. I am able to pass-by-reference to
the first function, addStudent() but then I am confused as to how I am
suppose to pass the pointer of 'student' from within the addStudent()
function to the getAge() function that is nested within the
addStudent() function.
You achieve the effect of pass-by-reference in C by explicitly passing
a pointer. Both your functions, addStudent() and getAge(), want to
receive a Student by reference, so they should both declare a
pointer-to-student as their argument.

So this is right:
>void addStudent(Stud ent *student) {
and this call is right:
addStudent(&stu dents[3]);
because students[3] is of type Student, so you have to use ampersand
to get a pointer to it.

This is wrong though:
>void getAge(Student **student) {
It should be Student *student, just as in addStudent(), and this call:
getAge(&student );
should just be getAge(student) because student is already a pointer.

By the way, this is a very bad idea in real code:
scanf("%s", student->name);
because it tries to read a string of unknown length. You declared
Student as:
>typedef struct {
char name[20];
int age;
} Student;
(did you mean to use NAME_SIZE which you defined as 20?), so what will
happen if the user type in a 30-character name? Look up scanf() to
see how to limit the string length.

-- Richard
--
:wq
Jun 27 '08 #2
"Richard Tobin" <ri*****@cogsci .ed.ac.ukwrote in message
news:g0******** ***@pc-news.cogsci.ed. ac.uk...
In article
<02************ *************** *******@i36g200 0prf.googlegrou ps.com>,
S. <si********@gma il.comwrote:
[...]
(did you mean to use NAME_SIZE which you defined as 20?), so what will
happen if the user type in a 30-character name? Look up scanf() to
see how to limit the string length.
Here is a simple way to setup fixed length string formatters in scanf what
will work with the NAME_SIZE macro:
_______________ _______________ _______________ _______________ ________
#include <stdio.h>

#define PLACE_X(t)t
#define PLACE(t)t
#define QUOTE_X2(t)#t
#define QUOTE_X1(t)PLAC E_X(QUOTE_X2)t
#define QUOTE(t)QUOTE_X 1((t))

#define NAME_SIZE 10

int main() {
char name[NAME_SIZE + 1] = { '\0' };
printf("Enter Name: ");
if (scanf(QUOTE(%P LACE(NAME_SIZE) s), name) == 1) {
printf("\n\nYou r Name Is: %s\n", name);
}
return 0;
}

_______________ _______________ _______________ _______________ ________

Jun 27 '08 #3
S.
Hi Richard,

Thank you so much. Your comments not only fixed my problem but also
helped me with understanding pointers.

You are also right about your other tips in regards to NAME_SIZE and
the name array. I am fixing those aspects of the code as we speak.

Kind regards,
S.

On May 11, 9:42 am, rich...@cogsci. ed.ac.uk (Richard Tobin) wrote:
In article <02f6dd75-4fd9-45f9-86dc-362fd84c5...@i3 6g2000prf.googl egroups.com>,

S. <sianeag...@gma il.comwrote:
I have the requirement that I must pass-by-reference to my function
addStudent() and getAge() functions where my getAge() function is
within the addStudent() function. I am able to pass-by-reference to
the first function, addStudent() but then I am confused as to how I am
suppose to pass the pointer of 'student' from within the addStudent()
function to the getAge() function that is nested within the
addStudent() function.

You achieve the effect of pass-by-reference in C by explicitly passing
a pointer. Both your functions, addStudent() and getAge(), want to
receive a Student by reference, so they should both declare a
pointer-to-student as their argument.

So this is right:
void addStudent(Stud ent *student) {

and this call is right:
addStudent(&stu dents[3]);

because students[3] is of type Student, so you have to use ampersand
to get a pointer to it.

This is wrong though:
void getAge(Student **student) {

It should be Student *student, just as in addStudent(), and this call:
getAge(&student );

should just be getAge(student) because student is already a pointer.

By the way, this is a very bad idea in real code:
scanf("%s", student->name);

because it tries to read a string of unknown length. You declared
Student as:
typedef struct {
char name[20];
int age;
} Student;

(did you mean to use NAME_SIZE which you defined as 20?), so what will
happen if the user type in a 30-character name? Look up scanf() to
see how to limit the string length.

-- Richard
--
:wq
Jun 27 '08 #4
S. said:
Hi all,

I have the requirement that I must pass-by-reference to my function
Tricky, that, in C. C uses pass-by-value for all parameter-passing.

<snip>
My code below does not compile correctly with the inclusion of the
getAge() function and I receive the following compile warning:
"test2.c", line 30: warning: left operand of "->" must be pointer
to struct/union
where line 30 is:
scanf("%d", student->age);
Let's take a look at the student object, then, shall we?
typedef struct {
char name[20];
int age;
} Student;
Presumably that's the type.
void addStudent(Stud ent *student);
void getAge(Student **student);

void main() {
In C, main returns int. Learn this. Mark it well. Engrave it on your heart,
your soul, and your wristwatch strap. In C, main returns int.
Student students[CLASS_SIZE];
addStudent(&stu dents[3]);
That's fine. students[3] is a Student object, so &students[3] is a pointer
to a Student object.
return;
}

/* Pass-by-reference */
void addStudent(Stud ent *student) {
That pointer sure looks to me as if it's being passed by value.
printf("\nStude nt name: ");
scanf("%s", student->name);
Unwise. Anyone who types in a name as long as ZoroastrianPent angle (or
anything longer) will overrun memory that it shouldn't, possibly resulting
in bizarre outcomes. I recommend you do some research into fgets.
printf("\nStude nt age: ");
getAge(&student );
Okay, that's legal, and passes a copy of the VALUE of the address of this
pointer to getAge().
return;
}

/* Pass-by-reference */
Sure looks like pass-by-value to me.
void getAge(Student **student) {
scanf("%d", student->age);
-requires on its left side a pointer to struct. You don't have one. You
have a pointer to pointer to struct. This will work:

int getAge(Student **student) {
return scanf("%d", &(*student)->age);
}

(note the & because scanf requires a pointer to a valid int, not the int
value itself) but one wonders why you are bothering to do this, since you
don't use the fact that, in this getAge function, student is a pointer to
a pointer. Why not lose a * and just do:

int getAge(Student *student) {
return scanf("%d", &student->age);
}

and make appropriate adjustments in the caller? If your reason is that
"then it wouldn't be pass by reference", well, it isn't pass by reference
anyway, so no loss there. In fact, why not just pass a pointer to the age?

int getAge(int *ageptr) {
return scanf("%d", ageptr);
}

In fact, why bother with the function at all?

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jun 27 '08 #5

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

Similar topics

0
1331
by: uli2003wien | last post by:
Dear group, PASS (SQL-Server user group) is about to start founding a branch in Vienna. I went to SQLCON and met some guys from the German PASS group and decided to become a member of PASS, decided to look for other individuals to take part in an Austrian branch of PASS based in Vienna, so whoever is interested may take a look at http://www.sqlpass.de/Default.aspx?tabid=191 in order to get to contact me to get things going....
8
2610
by: Tcs | last post by:
I've been stumped on this for quite a while. I don't know if it's so simple that I just can't see it, or it's really possible. (Obviously, I HOPE it IS possible.) I'm trying to get my queries to run from VB. My pass-thru query retrieves data from our AS/400 that I use to build a local table (on my PC). My pass-thru and local do in fact work together when I run them interactively. But I want, no make that NEED, to run them from VB. ...
2
17087
by: Alex Nitulescu | last post by:
Hi. I have tried to pass two parameters, like this: Response.Redirect(String.Format("NewPage.aspx?Username={0}, Pass={1}", txtUserName.Text, txtPass.Text)) But if I pass Username="Alex" and Pass="AAA", I get Params("Username") = "alex, Pass=AAA" and Params("Pass")="", which is not what I expected.
3
5476
by: Brett | last post by:
I have several classes that create arrays of data and have certain properties. Call them A thru D classes, which means there are four. I can call certain methods in each class and get back an array of data. All four classes are the same except for the number of elements in their arrays and the data. I have a MainClass (the form), which processes all of these arrays. The MainClass makes use of third party objects to do this. There...
4
2242
by: Marcelo | last post by:
Any suggestion? Thanks Marcelo
3
12591
by: ILCSP | last post by:
Hello, I'm fairly new to the concept of running action pass through queries (insert, update, etc.) from Access 2000. I have a SQL Server 2000 database and I'm using a Access 2K database as my front end. I'm using a blank pass through query which gets the Transact-SQL part inserted from a button in my form. After inserting the Transact-SQL code into the pass through query, I 'open the recordset' to make the query run. However,...
5
6316
by: marshmallowww | last post by:
I have an Access 2000 mde application which uses ADO and pass through queries to communicate with SQL Server 7, 2000 or 2005. Some of my customers, especially those with SQL Server 2005, have had pass-through queries fail due to intermittent connection failures. I can easily restablish a connection for ADO. My problem is with pass-through queries.
5
15603
by: Remote_User | last post by:
Hi, Is there any way I can pass a file as a parameter? ( maybe read it into a object) I am working on C# VS2005. Thanks.
14
3600
by: =?Utf-8?B?Umljaw==?= | last post by:
I have seen examples of passing data from FormB to FormA (Parent To Child) but I need an example of passind data from FormA to FormB. My main form is FormA; I will enter some data in textboxes and click a button to bring up FormB which needs to display values entered in FormA. Thanks in advance.
13
3724
by: magickarle | last post by:
Hi, I got a pass-through query (that takes about 15 mins to process) I would like to integrate variables to it. IE: something simple: Select EmplID from empl_Lst where empl_lst.timestamp between !! And !! Not sure how to do so (should it be a query in Access or a macro) The connection would be ODBC.
0
8367
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8279
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8811
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8589
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5619
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4145
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4291
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2703
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
2
1591
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.