Acknowledgement: MR Setu Maheshwari For His Advices and Patiently Guiding Me Through
Acknowledgement: MR Setu Maheshwari For His Advices and Patiently Guiding Me Through
I wish learnt a lot of valuable things while working here. I realize that
learning is never the same when it comes to practice.
I wish to extend my sincere gratitude to Dr Ruchi Singla (HOD) ECE and
faculty of ECE department for their guidance , encouragement and
valuable suggestion which proved extremely useful and helpful in
completion of this industrial training.
Utkarsh kapoor
1533370
. (B.tech 5th semester ece )
Table of Contents
QUICK START WITH C
MORE ON FUNCTIONS
FUNCTION ARGUMENTS
STRUCTURES
FILES
Quick Start with C
C programming language is perhaps the most popular programming language. C was
created in 1972 by
Dennis Ritchie at the Bell Labs in USA as a part of UNIX operating system. C was also
used to
develop some parts of this operating system. From that time C programming language
has been the
de facto programming language when fast programs are needed or the software needs
to interact
with the hardware in some way. Most of the operating systems like Linux, Windows™,
and Mac™ are either
developed in C language or use this language for most parts of the operating system
and the tools coming
with it.
This course is a quick course on C Programming language. In our first lesson we will
first write our first
C program. We will then learn about printing to screen, variables and functions. We
assume that you are
familiar with at least one of the popular operating systems.
For this course you can use the following compilers or Programming Environments.
Gcc and cc in Unix and Linux operating systems
Borland C or Turbo C in DOS operating system or in Command line environment of
windows
operating system
“Bloodshed Dev-Cpp” integrated development environment (IDE) gives you a
complete and
compact programming environment. It comes with “MinGW” and “GCC” C Compilers
and
you should not need anything else for this course.
We use “Bloodshed Dev-Cpp” for this course and we suggest you also use it.
“Bloodshed Dev-Cpp” is
free
.
Let's write our first C program.
Example
#include <stdio.h>
main()
{
printf("Hello World!\n");
system("pause"); //this line is only needed under windows
}
First step for running this program is to make a text file containing above code. Be sure
that the file is a
pure text file. You must save the text file with .c extension.
Then you must compile the source code. The result of compile step is an executable file
that you can
run it.
If you are running your example on Unix/Linux type operating systems you can remove
the line which
is commented to be necessary just under Windows.
Naming a variable
It is better that you use meaningful names for your variables even if this causes them to
become long
names. Also take this in mind that C is case sensitive. A variable named "COUNTER" is
different from
a variable named "counter".
Functions and commands are all case sensitive in C Programming language. You can
use letters, digits
and underscore _ character to make your variable names. Variable names can be up to
31 characters in
ANSI C language.
Q UIC K ST AR TW ITHC
9
The declaration of variables must take place just after the opening brace of a block. For
example we can
declare variables for main() function as below code:
main()
{
int count;
float sum,area;
.
.
.
}
First character in a variable name must be a letter or an underscore character. It cannot
be a C
programming language-reserved word (i.e. Commands and pre defined function names
etc). An example
for using variables comes below:
Example 1-2:
#include<stdio.h>
main()
{
int sum;
sum=12;
sum=sum+5;
printf("Sum is %d",sum);
system("pause");
}
General form for declaring a variable is:
Type name;
The line sum=sum+5; means: Increase value of sum by 5. We can also write this as
sum+=5; in C
programming language. printf function will print the following:
Sum is 17
In fact %d is the placeholder for integer variable value that its name comes after double
quotes.
Common data types are:
int integer
long long integer
float float number
double long float
char character
Other placeholders are:
Q UIC K ST AR TW ITHC
10
%d decimal integer
%ld decimal long integer
%s string or character array
%f float number
%e double (long float)
printf () function used in this example contains two sections. First section is a string
enclosed in double
quotes. It is called a format string. It determines output format for printf function. Second
section is
"variable list" section.
We include placeholders for each variable listed in variable list to determine its output
place in final
output text of printf function.
Control characters
As you saw in previous examples \n control character makes a new line in output. Other
control
characters are:
\n New line
\t tab
\r carriage return
\f form feed
\v vertical tab
Multiple functions
Look at this example:
Example
#include<stdio.h>
main()
{
printf("I am going inside test function now\n");
test();
printf("\nNow I am back from test function\n");
system("pause");
}
test()
{
int a,b;
a=1;
b=a+100;
printf("a is %d and b is %d",a,b);
}
Q UIC K ST AR TW ITHC
11
In this example we have written an additional function. We have called this function from
inside main
function. When we call the function, program continues inside test () function and after it
reached end
of it, control returns to the point just after test() function call in main(). You see declaring
a function and
calling it, is an easy task. Just pay attention that we used ";" when we called the function
but not when
we were declaring it.
We finish this lesson here. Now try to do lesson exercises and know the point that you
will not learn
anything if you do not do programming exercises.
Getting input, Arrays, Character
Strings and Preprocessors
n previous lesson you learned about variables and printing output results on computer
console. This
lesson discusses more about variables and adds important concepts on array of
variables, strings of
characters and preprocessor commands. We will also learn more on getting input
values from console
and printing output results after performing required calculations and processes. After
this lesson you
should be able to develop programs which get input data from user, do simple
calculations and print the
results on the output screen.
Variable Arrays
Arrays are structures that hold multiple variables of the same data type. An array from
integer type holds
integer values.
int scores[10];
The array "scores" contains an array of 10 integer values. We can use each member of
array by
specifying its index value. Members of above array are scores[0],...,scores[9] and we
can work with these
variables like other variables:
scores[0]=124;
scores[8]=1190;
Example 2-2
Receive 3 scores of a student in an array and finally calculate his average.
#include<stdio.h>
main()
{
int scores[3],sum;
float avg;
GETTIN GINPUT ,ARRAYS,STRI NGS…
14
printf("Enter Score 1 : ");
scanf("%d",&scores[0]);
printf("Enter Score 2 : ");
scanf("%d",&scores[1]);
printf("Enter Score 3 : ");
scanf("%d",&scores[2]);
sum=scores[0]+scores[1]+scores[2];
avg=sum/3;
printf("Sum is = %d\nAverage = %f\n",sum,avg);
system("pause");
}
Output results:
Enter Score 1 : 12
Enter Score 2 : 14
Enter Score 3 : 15
Sum is = 41
Average = 13.000000
Character Strings
In C language we hold names, phrases etc in character strings. Character strings are
arrays of characters.
Each member of array contains one of characters in the string. Look at this example:
Example 2-3
#include<stdio.h>
main()
{
char name[20];
printf("Enter your name : ");
scanf("%s",name);
printf("Hello, %s , how are you ?\n",name);
system("pause");
}
Output Results:
Enter your name : Brian
Hello, Brian, how are you ?
If user enters "Brian" then the first member of array will contain 'B' , second cell will
contain 'r' and so
on. C determines end of a string by a zero value character. We call this character as
"NULL" character
and show it with '\0' character. (It's only one character and its value is 0, however we
show it with two
characters to remember it is a character type, not an integer)
GETTIN GINPUT ,ARRAYS,STRI NGS…
15
Equally we can make that string by assigning character values to each member.
name[0]='B';
name[1]='r';
name[2]='i';
name[3]='a';
name[4]='n';
name[5]=0; //or name[5]='\0';
As we saw in above example placeholder for string variables is %s. Also we will not use
a '&' sign for
receiving string values. For now be sure to remember this fact and we will understand
the reason in
future lessons.
Preprocessor
Preprocessor statements are those lines starting with '#' sign. An example is
#include<stdio.h>
statement that we used to include stdio.h header file into our programs.
Preprocessor statements are processed by a program called preprocessor before
compilation step takes
place. After preprocessor has finished its job, compiler starts its work.
We have two kinds of variables from each of the above types in C programming
language: signed and
unsigned. Signed variables can have negative values too while unsigned values only
support positive
numbers.
If a signed variable is used, high boundary will be divided by two. This is because C will
divide the
available range to negative and positive numbers. For example signed int range is (-
32768,+32767).
You can declare a variable as “signed” or “unsigned” by adding "signed" or "unsigned"
keywords before
type name.
Example:
signed int a;
unsigned int b;
a=32700;
b=65000;
We are allowed to assign values larger than 32767 to variable "b" but not to variable "a".
C
programming language may not complain if we do so but program will not work as
expected.
Alternatively we can assign negative numbers to "a" but not to "b".
Default kind for all types is signed so we can omit signed keyword if we want a variable
to be signed.
Operators
There are many kinds of operators in each programming language. We mention some
of the operators
being used in C language here:
() Parentheses
+ Add
- Subtract
* Multiply
/ Divide
There are also some other operators which work differently:
% Modulus
++ Increase by one
-- Decrease by one
= Assignment
sizeof( ) return value is the size of a variable or type inside parentheses in bytes. It is
actually the size
that variable takes in system memory.
Examples:
c=4%3; c will be equal to 1 after execution of this command.
i=3;
i=i*3; i will be equal to 9
f=5/2; if f is integer then it will be equal to 2. If it
is a float type variable its value will be 2.5
j++; Increases the value of j by one.
19
j--; Decreases value of j by one
sizeof(int) returned value is 2 in dos and 4 in windows
int a=10;
c=sizeof(a); c will be 2 in dos and 4 in windows as the size of
integer
is different in different Os.
Loops
Sometimes we want some part of our code to be executed more than once. We can
either repeat the code in
our program or use loops instead. It is obvious that if for example we need to execute
some part of code for a
hundred times it is not practical to repeat the code. Alternatively we can use our
repeating code inside a loop.
while(not a hundred times)
{
code
}
There are a few kinds of loop commands in C programming language. We will see
these commands in next
sections.
While loop
while loop is constructed of a condition and a single command or a block of commands
that must run
in a loop. As we have told earlier a block of commands is a series of commands
enclosed in two
opening and closing braces.
while( condition )
command;
while( condition )
{
block of commands
}
Loop condition is a boolean expression. A boolean expression is a logical statement
which is either
correct or incorrect. It has a value of 1 if the logical statement is valid and its value is 0 if
it is not. For
example the Boolean statement (3>4) is invalid and therefore has a value of 0. While
the statement
(10==10) is a valid logical statement and therefore its value is 1.
Example 3-1#include<stdio.h>
main()
{
int i=0;
O P E RA TO RS ,L O O PS , TY PE C ON V ER S IO N
20
while( i<100 )
{
printf("\ni=%d",i);
i=i+1;
}
system("pause");
}
In above example i=i+1 means: add 1 to i and then assign it to i or simply increase its
value. As we saw
earlier, there is a special operator in C programming language that does the same thing.
We can use the
expression i++ instead of i=i+1.
We will learn more about logical operators in next lessons.
Type Conversion
From time to time you will need to convert type of a value or variable to assign it to a
variable from
another type. This type of conversions may be useful in different situations, for example
when you want
to convert type of a variable to become compatible with a function with different type of
arguments.
Some rules are implemented in C programming language for this purpose.
Automatic type conversion takes place in some cases. Char is automatically
converted to int.
Unsigned int will be automatically converted to int.
If there are two different types in an expression then both will convert to better type.
In an assignment statement, final result of calculation will be converted to the type of
the
variable which will hold the result of the calculation (ex. the variable “count” in the
assignment
count=i+1; )
For example if you add two values from int and float type and assign it to a double type
variable, result
will be double.
Using loops in an example
Write a program to accept scores of a person and calculate sum of them and their
average and print
them.
Example 3-2
#include<stdio.h>
main()
{
int count=0;
O P E RA TO RS ,L O O PS , TY PE C ON V ER S IO N
21
float num=0,sum=0,avg=0;
printf("Enter score (-1 to stop): ");
scanf("%f",&num);
while(num>=0)
{
sum=sum+num;
count++;
printf("Enter score (-1 to stop): ");
scanf("%f",&num);
}
avg=sum/count;
printf("\nAverage=%f",avg);
printf("\nSum=%f\n",sum);
system("pause");
}
In this example we get first number and then enter the loop. We will stay inside loop
until user enters a
value smaller than 0. If user enters a value lower than 0 we will interpret it as STOP
receiving scores.
Here are the output results of a sample run:
Enter score (-1 to stop): 12
Enter score (-1 to stop): 14
Enter score (-1 to stop): -1
Average=13.000000
Sum=26.000000
When user enters -1 as the value of num, logical expression inside loop condition
becomes false (invalid)
as num>=0 is not a valid statement.
Just remember that “while loop” will continue running until the logical condition inside its
parentheses
becomes false (and in that case it terminates).
For loop
As we told earlier, there are many kinds of loops in C programming language. We will
learn about for
loop in this section.
“For loop” is something similar to while loop but it is more complex. “For loop” is
constructed from a
control statement that determines how many times the loop will run and a command
section. Command
section is either a single command or a block of commands.
for( control statement )
command;
O P E RA TO RS ,L O O PS , TY PE C ON V ER S IO N
22
for( control statement )
{
block of commands
}
Control statement itself has three parts:
for ( initialization; test condition; run every time command )
Initialization part is performed only once at “for loop” start. We can initialize a loop
variable here. Test
condition is the most important part of the loop. Loop will continue to run if this condition
is valid
(True). If the condition becomes invalid (false) then the loop will terminate.
‘Run every time command’ section will be performed in every loop cycle. We use this
part to reach the
final condition for terminating the loop. For example we can increase or decrease loop
variable’s value
in a way that after specified number of cycles the loop condition becomes invalid and
“for loop” can
terminate.
At this step we rewrite example 3-1 with for loop. Just pay attention that we no more
need I=I+1 for
increasing loop variable. It is now included inside “for loop” condition phrase (i++).
Example
#include<stdio.h>
main()
{
int i=0;
for(i=0;i<100;i++ )
printf("\ni=%d",i);
system("pause");
}
Example 3-4
Write a program that gets temperatures of week days and calculate average
temperature for that week.
#include<stdio.h>
main()
{
int count=0;
float num=0,sum=0,avg=0;
for(count=0;count<7;count ++)
{
printf("Enter temperature : ");
O P E RA TO RS ,L O O PS , TY PE C ON V ER S IO N
23
scanf("%f",&num);
sum=sum+num;
}
avg=sum/7;
printf("\nAverage=%f\n",avg);
system("pause");
}
In next lesson we will learn more examples about using loops and also other control
structures.
End Note
I want to use the opportunity and give you a caution at the end of this lesson. As there
are many
commands and programming techniques in any programming language, you will not be
able to
remember all of them. The only way to remember things is to practice them. You need
to start
developing your own small programs. Start with lesson exercises and continue with
more sophisticated
ones. If you do not do this, all your efforts will become useless in a while.
I always quote this in my programming classes: "No one becomes a programmer
without
programming"
Selection using Switch Statements
n previous lesson we saw how we can use "if" statement in programs when they need
to choose an
option from among several alternatives. There is an alternative C programming
command which in
some cases can be used as an alternate way to do this. “Switch…case” command is
more readable and
easier language structure.
"Switch ... case" structure
We can use "if" statement yet but it is better to use "switch" statement which is created
for situations
that there are several choices.
switch(...)
{
case ... : command;
command;
break;
case ... : command;
break;
default:
command;
}
In the above switch command we will be able to run different series of commands with
each different
case.
Example 5-1:
Rewrite example 4-5 of previous lesson and use switch command instead of "if"
statement.
#include<stdio.h>
#include<stdlib.h>
main()
{
int choice;
while
{
printf("\n\nMenu:\n");
printf("1- Math Program\n2- Accounting Program\n");
printf("3- Entertainment Program\n4- Exit");
printf("\n\nYour choice -> ");
scanf("%d",&choice);
switch(choice)
{
case 1 : printf("\nMath Program Runs. !");
break;
case 2 : printf("\nAccounting Program Runs. !");
break;
case 3 : printf("\nEntertainment Program Runs. !");
break;
case 4 : printf("\nProgram Ends. !");
exit(0);
default:
printf("\nInvalid choice");
}
}
}
In "switch…case" command, each “case” acts like a simple label. A label determines a
point in program
which execution must continue from there. Switch statement will choose one of “case”
sections or
labels from where the execution of the program will continue. The program will continue
execution
until it reaches “break” command.
"break" statements have vital rule in switch structure. If you remove these statements,
program
execution will continue to next case sections and all remaining case sections until the
end of "switch"
block will be executed (while most of the time we just want one “case” section to be
run).
As we told, this is because each “case” acts just as a label. The only way to end
execution in switch block
is using break statements at the end of each “case” section.
In one of case sections we have not used "break". This is because we have used a
termination
command "exit(0)" (which terminates program execution) and a break statement will not
make any
difference.
"default" section will be executed if none of the case sections match switch comparison.
Parameter inside “switch” statement must be of type “int or char” while using a variable
in “case
sections” is not allowed at all. This means that you are not allowed to use a statement
like below one in
your switch block.
case i: something;
break;
Break statement
We used "break" statement in “switch...case” structures in previous part of this lesson.
We can also use
"break" statement inside loops to terminate a loop and exit it (with a specific condition).
Example 5-2: example5-2.c
while (num<20)
{
printf("Enter score : ");
scanf("%d",&scores[num]);
if(scores[num]<0)
break;
}
In above example loop execution continues until either num>=20 or entered score is
negative. Now see
another example.
Example 5-3:
#include<stdio.h>
#include<stdlib.h>
main()
{
int choice;
while(1)
{
printf("\n\nMenu:\n");
printf("1- Math Program\n2- Accounting Program\n");
printf("3- Entertainment Program\n4- Exit");
printf("\n\nYour choice -> ");
scanf("%d",&choice);
switch(choice)
{
case 1 : printf("\nMath Program Runs. !");
break;
case 2 : printf("\nAccounting Program Runs. !");
break;
S E LE C TIO NU SI NG S WIT CHS TA TE M EN TS
33
case 3 : printf("\nEntertainment Program Runs. !");
break;
case 4 : printf("\nProgram Ends. !");
break;
default:
printf("\nInvalid choice");
}
if(choice==4) break;
}
}
In above example we have used a break statement instead of exit command used in
previous example.
Because of this change, we needed a second break statement inside while loop and
outside switch block.
If the choice is 4 then this second “break command” will break while loop and we reach
the end of main
function and when there is no more statements left in main function program terminates
automatically.
getchar() and getch()
getchar() function is an alternative choice when you want to read characters from input.
This function
will get single characters from input and return it back to a variable or expression in our
program.
ch=getchar();
There is a function for sending characters to output too.
putchar(ch);
Example 5-4:
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
while(ch!='.')
{
ch=getchar();
putchar(ch);
}
system("pause");
}
First look at output results and try to guess the reason for results. Console Screen:
test <--This is typed by us
test <--output of putchar after we pressed enter
again.testing <--Typed string includes a '.' character
again. <--Loop terminates when it reaches '.' char
Above program reads any character that you have typed on keyboard until it finds a '.'
character in input
characters. Each key press will be both shown on console and added to a buffer. This
buffer will be
delivered to 'ch' variable after pressing enter key (not before this). So input characters
are buffered until
we press enter key and at that moment program execution continues running
statements that follow
getchar() function (These are loop statements).
If there is a '.' character in buffered characters, loop execution continues sending
characters to console
with putchar() function until it reaches '.' and after that stops the loop and comes out of
while loop.
If it does not encounter '.' in characters it returns to the start of loop, where it starts
getchar() function
again and waits for user input.
First 'test' string appeared in output is the result of our key presses and second 'test' is
printed by
putchar statement after pressing enter key.
In some operating systems and some C Programming language compilers, there is
another character
input function "getch". This one does not buffer input characters and delivers them as
soon as it
receives them. (in Borland C you need to include another header file <conio.h> to make
this new
function work).
Example 5-5:
#include<stdio.h>
main()
{
char ch;
while(ch!='.')
{
ch=getch();
putch(ch);
}
system("pause");
}
Testing. <--program terminates immediately after we use the
character ‘.', also characters are sent to output once
S E LE C TIO NU SI NG S WIT CHS TA TE M EN TS
35
With this function we can also check validity of each key press before accepting and
using it. If it is not
valid we can omit it. Just pay attention that some compilers do not support getch().
(again Borland c
needs the header file conio.h to be included)
Look at below example.
Example 5-6:
#include<stdio.h>
#include<stdlib.h>
main()
{
char choice;
while(1)
{
printf("\n\nMenu:\n");
printf("1- Math Program\n2- Accounting Program\n");
printf("3- Entertainment Program\n4- Exit");
printf("\n\nYour choice -> ");
choice=getch();
switch(choice)
{
case '1' : printf("\nMath Program Runs. !");
break;
case '2' : printf("\nAccounting Program Runs. !");
break;
case '3' : printf("\nEntertainment Program Runs. !");
break;
case '4' : printf("\nProgram Ends. !");
exit(0);
}
}
}
In above example we have rewritten example 5-1. This time we have used getch()
function instead of
scanf() function. If you test scanf based example you will see that it does not have any
control on
entered answer string. If user inserts an invalid choice or string (a long junk string for
example), it can
corrupt the screen. In getch function, user can insert one character at a time. Program
immediately gets
the character and tests it to see if it matches one of the choices.
In this example we have omitted optional "default" section in “switch...case”. Pay careful
attention that
in scanf based example we used to get an integer number as the user choice while here
we get a
character input. As a result previously we were using integer variable in “switch section”
and integer
numbers in “case sections”. Here we need to change the “switch … case” to match the
character type
data. So our switch variable is of char type and values being compared are used like '1',
'2', '3', '4' because
they are character type data ('1' character is different from the integer value 1).
If user presses an invalid key while loop will continue without entering any of "case"
sections. Invalid
key press will be omitted and only valid key presses will be accepted.
"continue" statement
Continue statement can be used in loops. Like break command "continue" changes flow
of a program.
It does not terminate the loop however. It just skips the rest of current iteration of the
loop and returns
to starting point of the loop.
Example 5-7:
#include<stdio.h>
main()
{
while((ch=getchar())!='\n')
{
if(ch=='.')
continue;
putchar(ch);
}
system("pause");
}
In above example, program accepts all input but omits the '.' character from it. The text
will be echoed
as you enter it but the main output will be printed after you press the enter key (which is
equal to
inserting a "\n" character) is pressed. As we told earlier this is because getchar()
function is a buffered
input function.
More on Functions
N lesson 1 we that each C program consists of one or more functions. main() is a
special function
because program execution starts from it.
A function is combined of a block of code that can be called or used anywhere in the
program by
calling the name. Body of a function starts with ‘{‘ and ends with ‘}’ . This is similar to the
main
function in our previous programs. Example below shows how we can write a simple
function.
Example
#include<stdio.h>
/*Function prototypes*/
myfunc();
main()
{
myfunc();
system("pause");
}
myfunc()
{
printf("Hello, this is a test\n");
}
In above example we have put a section of program in a separate function. Function
body can be very
complex though. After creating a function we can call it using its name. Functions can
also call each
other. A function can even call itself. This is used in recursive algorithms using a
termination condition
(to avoid the program to enter in an infinite loop). For the time being do not call a
function from inside
itself.
By the way pay attention to “function prototypes” section. In some C compilers we are
needed to
introduce the functions we are creating in a program above the program. Introducing a
function is being
called “function prototype”.
Call by value
C programming language function calls, use call by value method. Let’s see an example
to understand
this subject better.
Example
#include<stdio.h>
void test(int a);
main()
{
int m;
m=2;
printf("\nM is %d",m);
test(m);
printf("\nM is %d\n",m);
system("pause");
return 0;
}
void test(int a)
{
a=5;
}
In main() function, we have declared a variable m. We have assigned value ‘2’ to m. We
want to see if
function call is able to change value of ‘m’ as we have modified value of incoming
parameter inside test()
function. What do you think?
Program output result is:
M is 2
M is 2
So you see function call has not changed the value of argument. This s is because
function-calling
method only sends “value of variable” m to the function and it does not send variable
itself. Actually it
places value of variable m in a memory location called stack and then function retrieves
the value
without having access to main variable itself. This is why we call this method of calling
“call by value”.
Call by reference
There is another method of sending variables being called “Call by reference”. This
second method
enables function to modify value of argument variables used in function call.
We will first see an example and then we will describe it.
Example
#include<stdio.h>
void test(int *ptr);
main()
{
int m;
m=2;
printf("\nM is %d",m);
test(&m);
printf("\nM is %d\n",m);
system("pause");
return 0;
}
void test(int *ptr)
{
printf("\nModifying the value inside memory address %ld",&m);
*ptr=5;
}
To be able to modify the value of a variable used as an argument in a function, function
needs to know
memory address of the variable (where exactly the variable is situated in memory).
In C programming language ‘&’ operator gives the address at which the variable is
stored. For example
if ‘m’ is a variable of type ‘int’ then ‘&m’ will give us the starting memory address of our
variable. We
call this resulting address ‘a pointer’.
ptr=&m;
In above command ptr variable will contain memory address of variable m. This method
is used in some
of standard functions in C. For example scanf function uses this method to be able to
receive values
from console keyboard and put it in a variable. In fact it places received value in
memory location of the
variable used in function. Now we understand the reason why we add ‘&’ sign before
variable names in
scanf variables.
Scanf(“%d”,&a);
Now that we have memory address of variable we must use an operator that enables us
to assign a value
or access to value stored in that address.
As we told, we can find address of variable ‘a’ using ‘&’ operator.
ptr=&a;
FU NCT IONARGUM ENTS
47
Now we can find value stored in variable ‘a’ using ‘*’ operator:
Val=*ptr; /* finding the value ptr points to */
We can even modify the value inside the address:
*ptr=5;
Let’s look at our example again. We have passed pointer (memory address) to function.
Now function is
able to modify value stored inside variable. If you run the program, you will get these
results:
M is 2
Modifying the value inside memory address 2293620
M is 5
So you see this time we have changed value of an argument variable inside the called
function (by
modifying the value inside the memory location of our main variable).