Showing posts with label to. Show all posts
Showing posts with label to. Show all posts

Friday, October 1, 2010

Passing Entire Structures to Functions in C,C++

When a structure is used as an argument to a function, the entire structure is passed
using the standard call-by-value method. Of course, this means that any changes 

made to the contents of the structure inside the function to which it is passed do not
affect the structure used as an argument.
When using a structure as a parameter, remember that the type of the argument
must match the type of the parameter. For example, in the following program both the
argument arg and the parameter parm are declared as the same type of structure.
#include <stdio.h>
/* Define a structure type. */
struct struct_type {
int a, b;
char ch;
} ;
void f1(struct struct_type parm);
int main(void)
{
struct struct_type arg;
arg.a = 1000;
f1(arg);
return 0;
}
void f1(struct struct_type parm)
{
printf("%d", parm.a);
}
As this program illustrates, if you will be declaring parameters that are structures,
you must make the declaration of the structure type global so that all parts of your
program can use it. For example, had struct_type been declared inside main() (for
example), then it would not have been visible to f1().
As just stated, when passing structures, the type of the argument must match
the type of the parameter. It is not sufficient for them to simply be physically similar;
their type names must match. For example, the following version of the preceding
program is incorrect and will not compile because the type name of the argument
used to call f1() differs from the type name of its parameter.

/* This program is incorrect and will not compile. */
#include <stdio.h>
/* Define a structure type. */
struct struct_type {
int a, b;
char ch;
} ;
/* Define a structure similar to struct_type,
but with a different name. */
struct struct_type2 {
int a, b;
char ch;
} ;
void f1(struct struct_type2 parm);
int main(void)
{
struct struct_type arg;
arg.a = 1000;
f1(arg); /* type mismatch */
return 0;
}
void f1(struct struct_type2 parm)
{
printf("%d", parm.a);

Passing Structure Members to Functions in C,C++

When you pass a member of a structure to a function, you are actually passing
the value of that member to the function. Therefore, you are passing a simple
variable (unless, of course, that element is compound, such as an array). For
example, consider this structure:
struct fred
{
char x;
int y;
float z;
char s[10];
} mike;
Here are examples of each member being passed to a function:
func(mike.x); /* passes character value of x */
func2(mike.y); /* passes integer value of y */
func3(mike.z); /* passes float value of z */
func4(mike.s); /* passes address of string s */
func(mike.s[2]); /* passes character value of s[2] */
If you wish to pass the address of an individual structure member, put the & operator
before the structure name. For example, to pass the address of the members of the
structure mike, write
func(&mike.x); /* passes address of character x */
func2(&mike.y); /* passes address of integer y */
func3(&mike.z); /* passes address of float z */
func4(mike.s); /* passes address of string s */
func(&mike.s[2]); /* passes address of character s[2] */
Remember that the & operator precedes the structure name, not the individual
member name. Note also that s already signifies an address, so no & is required.

Wednesday, September 29, 2010

argc and argv—Arguments to main( )

Sometimes it is useful to pass information into a program when you run it. Generally,
you pass information into the main() function via command line arguments. A
command line argument is the information that follows the program's name on the
command line of the operating system. For example, when you compile a program,
you might type something like the following after the command prompt:
cc program_name
where program_name is a command line argument that specifies the name of the
program you wish to compile.
There are two special built-in arguments, argv and argc, that are used to receive
command line arguments. The argc parameter holds the number of arguments on

the command line and is an integer. It is always at least 1 because the name of the
program qualifies as the first argument. The argv parameter is a pointer to an array of
character pointers. Each element in this array points to a command line argument. All
command line arguments are strings—any numbers will have to be converted by the
program into the proper internal format. For example, this simple program prints
Hello and your name on the screen if you type it directly after the program name.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if(argc!=2) {
printf("You forgot to type your name.\n");
exit(1);
}
printf("Hello %s", argv[1]);
return 0;
}
If you called this program name and your name were Tom, you would type name Tom
to run the program. The output from the program would be Hello Tom.
In many environments, each command line argument must be separated by a space
or a tab. Commas, semicolons, and the like are not considered separators. For example,
run Spot, run
is made up of three strings, while
Herb,Rick,Fred
is a single string since commas are not generally legal separators.
Some environments allow you to enclose within double quotes a string containing
spaces. This causes the entire string to be treated as a single argument. Check your
operating system documentation for details on the definition of command line
parameters for your system.
You must declare argv properly. The most common method is
char *argv[];

The empty brackets indicate that the array is of undetermined length. You can now
access the individual arguments by indexing argv. For example, argv[0] points to the
first string, which is always the program's name; argv[1] points to the first argument,
and so on.
Another short example using command line arguments is the program called
countdown, shown here. It counts down from a starting value (which is specified on
the command line) and beeps when it reaches 0. Notice that the first argument
containing the number is converted into an integer by the standard function atoi() .If
the string "display" is the second command line argument, the countdown will also be
displayed on the screen.
/* Countdown program. */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main(int argc, char *argv[])
{
int disp, count;
if(argc<2) {
printf("You must enter the length of the count\n");
printf("on the command line. Try again.\n");
exit(1);
}
if(argc==3 && !strcmp(argv[2], "display")) disp = 1;
else disp = 0;
for(count=atoi(argv[1]); count; --count)
if(disp) printf("%d\n", count);
putchar('\a'); /* this will ring the bell */
printf("Done");
return 0;
}
Notice that if no command line arguments have been specified, an error message is
printed. A program with command line arguments often issues instructions if the
user attempts to run the program without entering the proper information.
To access an individual character in one of the command line arguments, add a
second index to argv. For example, the next program displays all of the arguments
with which it was called, one character at a time:

#include <stdio.h>
int main(int argc, char *argv[])
{
int t, i;
for(t=0; t<argc; ++t) {
i = 0;
while(argv[t][i]) {
putchar(argv[t][i]);
++i;
}
printf("\n");
}
return 0;
}
Remember, the first index accesses the string, and the second index accesses the
individual characters of the string.
Normally, you use argc and argv to get initial commands into your program. In
theory, you can have up to 32,767 arguments, but most operating systems do not allow
more than a few. You typically use these arguments to indicate a filename or an option.
Using command line arguments gives your program a professional appearance and
facilitates its use in batch files.
When a program does not require command line parameters, it is common
practice to explicitly declare main() as having no parameters. For C programs this is
accomplished by using the void keyword in its parameter list. (This is the approach
used by the programs in Part One of this book.) However, for C++ programs you
may simply specify an empty parameter list. In C++, the use of void to indicate an
empty parameter list is allowed, but redundant.
The names argc and argv are traditional but arbitrary. You may name these two
parameters to main() anything you like. Also, some compilers may support additional
arguments to main() , so be sure to check your user's manual.

Monday, September 27, 2010

argc and argv—Arguments to main( )

Sometimes it is useful to pass information into a program when you run it. Generally,
you pass information into the main() function via command line arguments. A
command line argument is the information that follows the program's name on the
command line of the operating system. For example, when you compile a program,
you might type something like the following after the command prompt:
cc program_name
where program_name is a command line argument that specifies the name of the
program you wish to compile.
There are two special built-in arguments, argv and argc, that are used to receive
command line arguments. The argc parameter holds the number of arguments on
the command line and is an integer. It is always at least 1 because the name of the
program qualifies as the first argument. The argv parameter is a pointer to an array of
character pointers. Each element in this array points to a command line argument. All
command line arguments are strings—any numbers will have to be converted by the
program into the proper internal format. For example, this simple program prints
Hello and your name on the screen if you type it directly after the program name.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if(argc!=2) {
printf("You forgot to type your name.\n");
exit(1);
}
printf("Hello %s", argv[1]);
return 0;
}
If you called this program name and your name were Tom, you would type name Tom
to run the program. The output from the program would be Hello Tom.
In many environments, each command line argument must be separated by a space
or a tab. Commas, semicolons, and the like are not considered separators. For example,
run Spot, run
is made up of three strings, while
Herb,Rick,Fred
is a single string since commas are not generally legal separators.
Some environments allow you to enclose within double quotes a string containing
spaces. This causes the entire string to be treated as a single argument. Check your
operating system documentation for details on the definition of command line
parameters for your system.
You must declare argv properly. The most common method is
char *argv[];
The empty brackets indicate that the array is of undetermined length. You can now
access the individual arguments by indexing argv. For example, argv[0] points to the
first string, which is always the program's name; argv[1] points to the first argument,
and so on.
Another short example using command line arguments is the program called
countdown, shown here. It counts down from a starting value (which is specified on
the command line) and beeps when it reaches 0. Notice that the first argument
containing the number is converted into an integer by the standard function atoi() .If
the string "display" is the second command line argument, the countdown will also be
displayed on the screen.
/* Countdown program. */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main(int argc, char *argv[])
{
int disp, count;
if(argc<2) {
printf("You must enter the length of the count\n");
printf("on the command line. Try again.\n");
exit(1);
}
if(argc==3 && !strcmp(argv[2], "display")) disp = 1;
else disp = 0;
for(count=atoi(argv[1]); count; --count)
if(disp) printf("%d\n", count);
putchar('\a'); /* this will ring the bell */
printf("Done");
return 0;
}
Notice that if no command line arguments have been specified, an error message is
printed. A program with command line arguments often issues instructions if the
user attempts to run the program without entering the proper information.
To access an individual character in one of the command line arguments, add a
second index to argv. For example, the next program displays all of the arguments
with which it was called, one character at a time:


#include <stdio.h>
int main(int argc, char *argv[])
{
int t, i;
for(t=0; t<argc; ++t) {
i = 0;
while(argv[t][i]) {
putchar(argv[t][i]);
++i;
}
printf("\n");
}
return 0;
}
Remember, the first index accesses the string, and the second index accesses the
individual characters of the string.
Normally, you use argc and argv to get initial commands into your program. In
theory, you can have up to 32,767 arguments, but most operating systems do not allow
more than a few. You typically use these arguments to indicate a filename or an option.
Using command line arguments gives your program a professional appearance and
facilitates its use in batch files.
When a program does not require command line parameters, it is common
practice to explicitly declare main() as having no parameters. For C programs this is
accomplished by using the void keyword in its parameter list. (This is the approach
used by the programs in Part One of this book.) However, for C++ programs you
may simply specify an empty parameter list. In C++, the use of void to indicate an
empty parameter list is allowed, but redundant.
The names argc and argv are traditional but arbitrary. You may name these two
parameters to main() anything you like. Also, some compilers may support additional
arguments to main() , so be sure to check your user's manual.

Sunday, September 26, 2010

Passing Single-Dimension Arrays to Functions In C/C++

In C/C++, you cannot pass an entire array as an argument to a function. You can,
however, pass to the function a pointer to an array by specifying the array's name
without an index. For example, the following program fragment passes the address of i
to func1() :
int main(void)
{
int i[10];
func1(i);
.
.
.
}
If a function receives a single-dimension array, you may declare its formal
parameter in one of three ways: as a pointer, as a sized array, or as an unsized array.
For example, to receive i, a function called func1() can be declared as void func1(int *x) /* pointer */
{
.
.
.
}
or
void func1(int x[10]) /* sized array */
{
.
.
.
}
or finally as
void func1(int x[]) /* unsized array */
{
.
.
.
}
All three declaration methods produce similar results because each tells the
compiler that an integer pointer is going to be received. The first declaration actually
uses a pointer. The second employs the standard array declaration. In the final version,
a modified version of an array declaration simply specifies that an array of type int of
some length is to be received. As you can see, the length of the array doesn't matter as
far as the function is concerned because C/C++ performs no bounds checking. In fact,
as far as the compiler is concerned,
void func1(int x[32])
{
.
.
.
}
also works because the compiler generates code that instructs func1() to receive a
pointer—it does not actually create a 32-element array.

Generating a Pointer to an Array

You can generate a pointer to the first element of an array by simply specifying the
array name, without any index. For example, given
int sample[10];
you can generate a pointer to the first element by using the name sample. Thus, the
following program fragment assigns p the address of the first element of sample:
int *p;
int sample[10];
p = sample;
You can also specify the address of the first element of an array using the &
operator. For example, sample and &sample[0] both produce the same results.
However, in professionally written C/C++ code, you will almost never see
&sample[0].