Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Array: Passing Arrays As Function Arguments in C

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

1

Array
C programming language provides a data structure called the array, which can store a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to
think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array
variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A
specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the
highest address to the last element.

Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an
array as follows:
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can
be any valid C data type. For example, to declare a 10-element array called balance of type double, use this
statement:
Passing Arrays as Function Arguments in C
f you want to pass a single-dimension array as an argument in a function, you would have to declare function formal
parameter in one of following three ways and all three declaration methods produce similar results because each tells
the compiler that an integer pointer is going to be received. Similar way you can pass multi-dimensional array as
formal parameters.
Way-1
void myFunction(int *param)
{
}
Way-2
void myFunction(int param[10])
{
}
Way-3
void myFunction(int param[])
{

}
C - Functions
A function is a group of statements that together perform a task. Every C program has at least one function, which
is main(), and all the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among different functions is up
to you, but logically the division usually is so each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call
A function is known with various names like a method or a sub-routine or a procedure, etc.
Defining a Function:
The general form of a function definition in C programming language is as follows:
return_type function_name( parameter list )
{
body of the function
}
2

A function definition in C programming language consists of a function header and a function body. Here are all the
parts of a function:
 Return Type: A function may return a value. The return_type is the data type of the value the function returns.
Some functions perform the desired operations without returning a value. In thiscase, the return_type is the
keyword void.
 Function Name: This is the actual name of the function. The function name and the parameter list together
constitute the function signature.
 Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This
value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may contain no parameters.
 Function Body: The function body contains a collection of statements that define what the function does.

Function Declarations:
A function declaration tells the compiler about a function name and how to call the function. The actual body of the
function can be defined separately.
A function declaration has the following parts:
return_type function_name( parameter list );
For the above defined function max(), following is the function declaration:

int max(int num1, int num2);


Parameter names are not important in function declaration only their type is required, so following is also valid
declaration:
int max(int, int);

Calling a Function:
While creating a C function, you give a definition of what the function has to do. To use a function, you will have
to call that function to perform the defined task.
When a program calls a function, program control is transferred to the called function. A called function performs
defined task and when its return statement is executed or when its function-ending closing brace is reached, it
returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name, and if function returns
a value, then you can store returned value
Function Arguments:
If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables
are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created upon entry into the
function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function:
Call Type Description
This method copies the actual value of an argument into the formal parameter of
Call by value the function. In this case, changes made to the parameter inside the function have
no effect on the argument.

This method copies the address of an argument into the formal parameter. Inside
Call by reference the function, the address is used to access the actual argument used in the call. This
means that changes made to the parameter affect the argument.
3

Advantages of Function
 Writing function avoid rewriting the same code over and over.
 By using functions it become easier to write programs and keep track of what they are doing. If the
operation of program can be divided into separate activities and each activity placed in different function
then, each could be written and checked more or less independently.
 Separating the code into modular function also make the program easier to design, Easier to debug, and
understand.
What Are Pointers?
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location.
Like any variable or constant, you must declare a pointer before you can use it to store any variable address. The
general form of a pointer variable declaration is:
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer variable.
The asterisk * you used to declare a pointer is the same asterisk that you use for multiplication. However, in this
statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration:
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long
hexadecimal number that represents a memory address. The only difference between pointers of different data types is the
data type of the variable or constant that the pointer points to.
How to use Pointers?
There are few important operations, which we will do with the help of pointers very frequently. (a) we define a pointer
variable (b) assign the address of a variable to a pointer and (c) finally access the value at the address available in the pointer
variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its
operand. Following example makes use of these operations:

Pointer Arithmetic
Assume int *int_ptr ;
/* Pointing to address 100 */
int_ptr++ ;
OR
int_ptr = int_ptr + 1 ;
Starts pointing to 102 location
int_ptr = int_ptr + 1 *(sizeof(int))
int_ptr = int_ptr + 2
int_ptr = 100 + 2
int_ptr = 102
Key Concept
Pointer increment/decrement changes value by sizeof(data type)

Legal and Illegal Operations


j = &300;
j = &(i + 300)
*(400) or *(i + 200 * j) // Legal
Lesson: Address Operator can be used with a variable only. Value at address or Indirection can be used on variables, constant
value or expression.
NULL Pointers in C
It is always a good practice to assign a NULL value to a pointer variable in case you do not have exact address to be
assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer.

The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the
following program:
4

C - Pointer to Pointer
A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer
contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the
second pointer, which points to the location that contains the actual value as shown below.

A variable that is a pointer to a pointer must be declared as such. This is done by placing an additionalasterisk in
front of its name. For example, following is the declaration to declare a pointer to a pointer of type int:
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the asterisk
operator be applied twice,

Passing pointers to functions in C


C programming language allows you to pass a pointer to a function. To do so, simply declare thefunction parameter
as a pointer type.
Following a simple example where we pass an unsigned long pointer to a function and change the value inside the
function which reflects back in the calling function:

#include <stdio.h>
#include <time.h>

void getSeconds(unsigned long *par);

int main ()
{
unsigned long sec;

getSeconds( &sec );

/* print the actual value */


printf("Number of seconds: %ld\n", sec );

return 0;
}

void getSeconds(unsigned long *par)


{
/* get the current number of seconds */
*par = time( NULL );
return;
}
Recursion vs Iteration
RECURSION ITERATIONS

Recursive function – is a function that is partially Iterative Instructions –are loop based repetitions
defined by itself of a process
Recursion Uses selection structure Iteration uses repetition structure
Infinite recursion occurs if the recursion step does not An infinite loop occurs with iteration if the loop-
reduce the problem in a manner that converges on condition test never becomes false
some condition.(base case)
Recursion terminates when a base case is recognized Iteration terminates when the loop-condition fails
5

Recursion is usually slower then iteration due to Iteration does not use stack so it's faster than
overhead of maintaining stack recursion
Recursion uses more memory than iteration Iteration consume less memory
Infinite recursion can crash the system infinite looping uses CPU
cycles repeatedly
Recursion makes code smaller Iteration makes code longer

Structures
We have used Array because it can hold data of same type or homogenous elements.
Is there any way we can combine these into a Single Entity?
Can we combine data of different types into a Single Entity?
One issue above is we have destroyed relationship between related fields.

Concept Program
struct employee {
int emplid ;
char name[50];
float salary ;
};
Space is not reserved during declaration, only definition allots
space in memory.
struct employee empl = {100, “Rahul”, 1000.50} ;
struct is a keyword
employee is the structure tag/name
emplid, name, salary are structure members
empl is a variable of the type structure
struct variables are user defined or derived variables
Emplid Name float
100 Rahul 1000.50
6
7
8
9

What is a file?
File – place on disc (secondary media) where group of related data is stored
E.g. your C programs, executables
High-level programming languages support file operations
 Naming,Opening,Reading,Writing
When a computer reads a file, it copies the file from the storage device to memory; when it
writes to a file, it transfers data from memory to the storage device.
Different modes
• Writing mode
– if file already exists then contents are deleted,
– else new file with specified name created
• Appending mode
– if file already exists then file opened with contents safe
– else new file created
• Reading mode
– if file already exists then opened with contents safe
– else error occurs.
Illustration
FILE *p1, *p2;
p1 = fopen(“data”,”r”);
p2= fopen(“results”, w”);
Additional modes
• r+ open to beginning for both reading/writing
• w+ same as w except both for reading and writing
• a+ same as ‘a’ except both for reading and writing
Files in ‘C’
• In C, each file is simply a sequential stream of bytes. C imposes
no structure on a file.
• A file must first be opened properly before it can be accessed for
reading or writing. When a file is opened, a stream is associated
with the file.
• Successfully opening a file returns a pointer to (i.e., the address
of) a file structure, which contains a file descriptor and a file
control block.
• The statement:
FILE *fptr1, *fptr2 ;
declares that fptr1 and fptr2 are pointer variables of type FILE.
Reading From Files
• In the following segment of C language code:
int a, b ;
FILE *fptr1, *fptr2 ;
fptr1 = fopen ( "mydata", "r" ) ;
fscanf ( fptr1, "%d%d", &a, &b) ;
the fscanf function would read values from the file "pointed" to by
fptr1 and assign those values to a and b.
End of File
• The end-of-file indicator informs the program when there are no
more data (no more bytes) to be processed.
• There are a number of ways to test for the end-of-file condition.
One is to use the feof function which returns a true or false
condition:
10

fscanf (fptr1, "%d", &var) ;


if ( feof (fptr1) )
{
printf ("End-of-file encountered.\n”);
}

You might also like