You are on page 1of 34

C Programming Arrays

In C programming, one of the frequently arising problem is to handle similar types of data.
For example: If the user want to store marks of 100 students. This can be done by creating
100 variable individually but, this process is rather tedious and impracticable. These type of
problem can be handled in C programming using arrays.
An array is a sequence of data item of homogeneous value(same type).
Arrays are of two types:
1. One-dimensional arrays
2. Multidimensional arrays( will be discussed in next chapter )

Declaration of one-dimensional array


data_type array_name[array_size];
For example:
int age[5];

Here, the name of array is age. The size of array is 5,i.e., there are 5 items(elements) of array
age. All element in an array are of the same type (int, in this case).

Array elements
Size of array defines the number of elements in an array. Each element of array can be
accessed and used by user according to the need of program. For example:
int age[5];

Note that, the first element is numbered 0 and so on.


Here, the size of array age is 5 times the size of int because there are 5 elements.
Suppose, the starting addres of age[0] is 2120d and the size of int be 4 bytes. Then, the next
address (address of a[1]) will be 2124d, address of a[2] will be 2128d and so on.

Initialization of one-dimensional array:


Arrays can be initialized at declaration time in this source code as:
int age[5]={2,4,34,3,4};

It is not necessary to define the size of arrays during initialization.


int age[]={2,4,34,3,4};

In this case, the compiler determines the size of array by calculating the number of elements
of an array.

Accessing array elements


In C programming, arrays can be accessed and treated like variables in C.
For example:
scanf("%d",&age[2]);
/* statement to insert value in the third element of array age[]. */
scanf("%d",&age[i]);
/* Statement to insert value in (i+1)th element of array age[]. */
/* Because, the first element of array is age[0], second is age[1], ith is
age[i-1] and (i+1)th is age[i]. */
printf("%d",age[0]);
/* statement to print first element of an array. */
printf("%d",age[i]);
/* statement to print (i+1)th element of an array. */

Example of array in C programming


/* C program to find the sum marks of n students using arrays */
#include <stdio.h>
int main(){
int marks[10],i,n,sum=0;
printf("Enter number of students: ");
scanf("%d",&n);
for(i=0;i<n;++i){
printf("Enter marks of student%d: ",i+1);
scanf("%d",&marks[i]);
sum+=marks[i];
}
printf("Sum= %d",sum);
return 0;
}

Output
Enter number of students: 3
Enter marks of student1: 12

Enter marks of student2: 31


Enter marks of student3: 2
sum=45

Important thing to remember in C arrays


Suppose, you declared the array of 10 students. For example: arr[10]. You can use array
members from arr[0] to arr[9]. But, what if you want to use element arr[10], arr[13]
etc. Compiler may not show error using these elements but, may cause fatal error during
program execution.
- See more at: http://www.programiz.com/c-programming/c-arrays#sthash.OeQF4Rhl.dpuf

C Programming - Handling of Character String


Author: Brian Moriya

Published on: 17th Apr 2006

| Last Updated on: 19th Jul 2011

In this tutorial you will learn about Initializing Strings, Reading Strings from the terminal,
Writing strings to screen, Arithmetic operations on characters, String operations (string.h),
Strlen() function, strcat() function, strcmp function, strcmpi() function, strcpy() function,
strlwr () function, strrev() function and strupr() function.
In C language, strings are stored in an array of char type along with the null terminating
character "\0" at the end. In other words to create a string in C you create an array of chars
and set each element in the array to a char value that makes up the string. When sizing the
string array you need to add plus one to the actual size of the string to make space for the null
terminating character, "\0"
Syntax to declare a string in C:
Sample Code
1.

char fname[4];
Copyright exforsys.com

The above statement declares a string called fname that can take up to 3 characters. It can be
indexed just as a regular array as well.
fname[] = {'t','w','o'};

Character

\0

ASCII Code

116

119

41

The last character is the null character having ASCII value zero.

Initializing Strings
To initialize our fname string from above to store the name Brian,
Sample Code
1.

char fname[31] = {"Brian"};


Copyright exforsys.com

You can observe from the above statement that initializing a string is same as with any array.
However we also need to surround the string with quotes.

Writing Strings to the Screen


To write strings to the terminal, we use a file stream known as stdout. The most common
function to use for writing to stdout in C is the printf function, defined as follows:
Sample Code
1.

int printf(const char *format, ...);


Copyright exforsys.com

To print out a prompt for the user you can:


Sample Code
1.

printf("Please type a name: \n");


Copyright exforsys.com

The above statement prints the prompt in the quotes and moves the cursor to the next line.
If you wanted to print a string from a variable, such as our fname string above you can do
this:

Sample Code
1.

printf("First Name: %s", fname);


Copyright exforsys.com

You can insert more than one variable, hence the "..." in the prototype for printf but this is
sufficient. Use %s to insert a string and then list the variables that go to each %s in your
string you are printing. It goes in order of first to last. Let's use a first and last name printing
example to show this:
Sample Code
1.

printf("Full Name: %s %s", fname, lname);


Copyright exforsys.com

The first name would be displayed first and the last name would be after the space between
the %s's.

Reading Strings from the Terminal


When we read a string from the terminal we read from a file stream known as stdin. *nix
users are probably familiar with this, it's how you can type a program name into the terminal
and pass it arguments also.
Say we want to allow the user to enter a name from stdin. Aside from taking the name as a
command line argument, we can use the scanf function which has the following prototype:
Sample Code
1.

int scanf(const char *format, ...);


Copyright exforsys.com

Note the similarity to printf.


Quick example to tie the last few sections together.
getname.c:
Sample Code
1. #include <stdio.h>

2.
3. void main() {
4.
5.

char fname[30];

6.

char lname[30];

7.
8.

printf("Type first name:\n");

9.

scanf("%s", fname);

10.
11.

printf("Type last name:\n");

12.

scanf("%s", lname);

13.
14.

printf("Your name is: %s %s\n", fname, lname);

15. }
Copyright exforsys.com

We declare two strings fname and lname. Then we use the printf function to prompt the user
for a first name. The scanf function takes the input from stdin and automatically exits once
the user presses enter. Then we repeat the above sequence except using the last name this
time. Finally we print the full name that was typed back to stdout. Should look something like
this:

Arithmetic Operations on Strings

Characters in C can be used just like integers when used with arithmetic operators. This is
nice, for example, in low memory applications because unsigned chars take up less memory
than do regular integers as long as your value does not exceed the rather limited range of an
unsigned char.
Let us cut to our example,
charmath.c:
Sample Code
1.

#include <stdio.h>

2.

void main() {

3.

unsigned char val1 = 20;

4.

unsigned char val2 = 30;

5.

int answer;

6.
7.

printf("%d\n", val1);

8.

printf("%d\n", val2);

9.
10.

answer = val1 + val2;

11.

printf("%d + %d = %d\n", val1, val2, answer);

12.
13.

val1 = 'a';

14.

answer = val1 + val2;

15.
16.
17.

printf("%d + %d = %d\n", val1, val2, answer);


}
Copyright exforsys.com

First we make two unsigned character variables and give them (rather low) number values.
We then add them together and put the answer into an integer variable. We can do this
without a cast because characters are an alphanumeric data type. Next we set var1 to an
expected character value, the letter lowercase a. Now this next addition adds 97 to 30, why?

Because the ASCII value of lowercase a is 97. So it adds 97 to 30, the current value in var2.
Notice it did not require casting the characters to integers or having the compiler complain.
This is because the compiler knows when to automatically change between characters and
integers or other numeric types.

String Operations
Character arrays are a special type of array that uses a "\0" character at the end. As such it has
it is own header library called string.h that contains built-in functions for performing
operations on these specific array types.
You must include the string header file in your programs to utilize this functionality.
Sample Code
1.

#include <string.h>
Copyright exforsys.com

We will cover the essential functions from this library over the next few sections.

Length of a String
Use the strlen function to get the length of a string minus the null terminating character.
Sample Code
1.

int strlen(string);
Copyright exforsys.com

If we had a string, and called the strlen function on it we could get its length.
Sample Code
1.

char fname[30] = {"Bob"};

2.

int length = strlen(fname);


Copyright exforsys.com

This would set length to 3.

Concatenation of Strings

The strcat function appends one string to another.


Sample Code
1.

char *strcat(string1, string2);


Copyright exforsys.com

The first string gets the second string appended to it. So for example to print a full name from
a first and last name string we could do the following:
Sample Code
1.

char fname[30] = {"Bob"};

2.

char lname[30] = {"by"};

3.

printf("%s", strcat(fname, lname));


Copyright exforsys.com

The output of this snippet would be "Bobby."

Compare Two Strings


Sometimes you want to determine if two strings are the same. For this we have the strcmp
function.
Sample Code
1.

int strcmp(string1, string2);


Copyright exforsys.com

The return value indicates how the 2 strings relate to each other. if they are equal strcmp
returns 0. The value will be negative if string1 is less than string2, or positive in the opposite
case.
For example if we add the following line to the end of our getname.c program:
Sample Code
1.

printf("%d", strcmp(fname, lname));


Copyright exforsys.com

When run on a Linux computer with the following first and last name combinations, the
program will yield the following output.
Sample Code
1.

First name: Bob, last name: bob, output: -1.

2.

First name: bob, last name: Bob, output 1.

3.

First name: Bob, last name: Bob, output 0.


Copyright exforsys.com

Compare Two Strings (Not Case Sensitive)


If you do not care whether your strings are upper case or lower case then use this function
instead of the strcmp function. Other than that, it's exactly the same.
Sample Code
1.

int strcmpi(string1, string2);


Copyright exforsys.com

Imagine using this function in place of strcmp in the above example, all of the first and last
combinations would output 0.

Copy Strings
To copy one string to another string variable, you use the strcpy function. This makes up for
not being able to use the "=" operator to set the value of a string variable.
Sample Code
1.

strcpy(string1, string2);
Copyright exforsys.com

To set the first name of our running example in code rather than terminal input we would use
the following:
Sample Code

1.

strcpy(fname, "Bob");
Copyright exforsys.com

Converting Uppercase Strings to Lowercase Strings


This function is not part of the ANSI standard and therefore strongly recommended against if
you want your code to be portable to platforms other than Windows.
Sample Code
1.

strlwr(string);
Copyright exforsys.com

This will convert uppercase characters in string to lowercase. So "BOBBY" would become
"bobby".

Reversing the Order of a String


This function is not part of the ANSI standard and therefore strongly recommended against if
you want your code to be portable to platforms other than Windows.
Sample Code
1.

strrev(string);
Copyright exforsys.com

Will reverse the order of string. So if string was "bobby", it would become "ybbob".

C Arithmetic Operators
Arithmetic operators include the familiar addition (+), subtraction (-), multiplication (*) and
division (/) operations. In addition there is the modulus operator (%) which gives the
remainder left over from a division operation. Let us look at some examples:

Sample Code
1.

#include <stdio.h>

2.
3.

void main()

4.

5.

int a = 100;

6.

int b = 3;

7.

int c;

8.
9.

c = a + b;

10.

printf( "a + b = %dn", c );

11.
12.

c = a - b;

13.

printf( "a - b = %dn", c );

14.
15.

/* multiplication performed before call to printf() */

16.

printf( "a * b = %dn", a * b );

17.
18.

c = a / b;

19.

printf( "a / b = %dn", c );

20.
21.

c = 100 % 3;

22.

printf( "a % b = %dn", c );

23. }
Copyright exforsys.com

Note Though the usual definition of the main() function is int main(), few compilers allow
the main() function to return void. The C standard allows for implementation defined
versions of main() that do not return int. If your compiler does not allow that, change line 3 to
int main() and put a return statement return 0; at the end just before line 23.

This program gives the following output:


a
a
a
a
a

+
*
/
%

b
b
b
b
b

=
=
=
=
=

103
97
300
33
1

In this example you can see on line 16 that it is not always necessary to assign the result of an
operation to a variable. The multiplication is performed first, then the result is passed to the
printf() function. On line 21 we see an example of using an operator on constants, with the
100 and 3 replacing the variables a and b.
If the modulus operator on line 21 is new to you, it is the remainder left over when one
integral number is divided by another. For example 45 % 6 is 3 since 6 * 7 is 42 and the
remainder is 3. The modulus operator works only with integral types (char, short, int, etc.). If
you try to use it with other types such as a float or double the compiler will give an error.
So far we have only used integers in our examples. When you use an operator on mixed types
they will be implicitly converted into a common type before the operation is performed. The
result of the operation will also be in the common type. The common type is derived using a
few rules, but generally, a smaller operand is converted to the larger operand's type. If the
result of the operation is assigned to another variable, the result is converted from the
common type to the type of that variable. Let us look at some examples:
Sample Code
1.

#include <stdio.h>

2.
3.

void main()

4.

5.

int a = 65000;

6.

char c = 120;

7.

int iresult;

8.

char cresult;

9.
10.

iresult = a + c;

11.

printf( "a + c = %dn", iresult );

12.
13.

cresult = a + c;

14.

printf( "a + c = %dn", cresult );

15. }
16.
Copyright exforsys.com

The output is:


a + c = 65120
a + c = 96

On the system where this example was run, an int type is a signed 32 bit number, and a char
type is a signed 8 bit number. When the a + c operation is performed, c is converted to an int
and then added to a, resulting in an another int.
On line 10 this integer is assigned to iresult, which is also an int so no conversion is
necessary.
On line 13 the result is assigned to a char, which means the int result must be converted into a
char. The binary representation of 65120 is 1111111001100000. Truncating this to just the
first 8 bits (since a char is 8 bits on this machine) gives 01100000 which is 96 in decimal.
Another example:
Sample Code
1.

#include <stdio.h>

2.
3.

void main()

4.

5.

int a = 4;

6.

float b = 3.14159;

7.

int iresult;

8.

float fresult;

9.
10.

fresult = a * b;

11.

printf( "a * b = %fn", fresult );

12.
13.

iresult = a * b;

14.

printf( "a * b = %dn", iresult );

15. }
Copyright exforsys.com

The output is:


a * b = 12.566360
a * b = 12

A similar process happens in this example. The integer a is converted to a float since a float is
capable of holding integers but not vice-versa. The result of the multiplication is a float,
which must be converted back to an int on line 13. This is done by truncating the fractional
part of the float.
This conversion process happens for constants too.
Sample Code
1.

#include <stdio.h>

2.
3.

void main()

4.

5.

double d = 15 / 6;

6.

printf( "15 / 6 is %fn", d );

7.
8.

d = 15.0 / 6;

9.

printf( "15 / 6 is %fn", d );

10.

}
Copyright exforsys.com

The output is:


15 / 6 is 2.000000
15 / 6 is 2.500000

On line 5 both the constants are integers, so an integer division is performed and then the
result converted to a double. On line 8 the 15.0 is a double constant which forces the division
to be done using double precision floating point numbers, and then the result assigned to d.

C Relational Operators
Relational operators compare operands and return 1 for true or 0 for false. The following
relational operators are available:
Symbol
<
>
<=
>=
==
!=

Meaning
Less than
Greater than
Less than or equal to
Greater than or equal to
Equal to
Not equal to

Here is an example of how to use these operators. This program is a simple number guessing
game:
Sample Code
1. #include <stdio.h>
2.

#include <stdlib.h>

3.

#include <time.h>

4.
5.

void main()

6.

7.

int mynum;

8.

int guess = -1;

9.

char buffer[64];

10.
11.

srand( time(0) );

12.

mynum = rand() % 100 + 1;

13.
14.

printf( "I have picked a number between 1-100.n" );

15.
16.

while( guess != mynum )

17.

18.

printf("Enter your guess: ");

19.

if ( fgets( buffer, 64, stdin ) == NULL )

20.

break;

21.

guess = atoi( buffer );

22.
23.

if ( guess >= 101 || guess <= 0 )

24.

25.

printf("Your guess is out of bounds.n");

26.

continue;

27.

28.
29.

if ( mynum > guess )

30.

printf("Your guess is too low.n");

31.

else if ( mynum < guess )

32.
33.

printf("Your guess is too high.n");


}

34.
35.
36.

if ( guess == mynum )
printf( "You guessed correctly.n" );

37. }
Copyright exforsys.com

The output from a typical run is shown here (user entered values in red):
I have picked a number between 1-100.
Enter your guess: 300
Your guess is out of bounds.
Enter your guess: 50
Your guess is too high.
Enter your guess: 25
Your guess is too low.
Enter your guess: 37
Your guess is too high.
Enter your guess: 31
Your guess is too high.
Enter your guess: 28
Your guess is too high.
Enter your guess: 26
You guessed correctly.

When the program is first run, the condition in the while loop on line 16 is satisfied because
guess was initialized to -1 on line 8 and lines 11-12 initialize mynum with a random number
between 1 and 100. Lines 18-21 tell the user to enter their guess and read the input from the
user.
The if statement on line 23 uses the or operator || which will be covered later it basically
says if the user enters a number greater than or equal to 101 or less than or equal to 0 then tell
the user the guess is invalid. The program will keep looping until the user guesses the right
value or there is an error reading input from the user (the break statement on line 20 breaks
out of the loop in that case).
You can compare values of different types. Just like with arithmetic operations, the operands
are converted to a common type and then compared.
Sample Code
1.

#include <stdio.h>

2.
3.

void main()

4.

5.

double dnum = 5.1;

6.
7.

if ( ( dnum > 5 ) == 1 )

8.

printf( "%lf > 5n", dnum );

9.

else

10. printf( "%lf <= 5n", dnum );


11. }
Copyright exforsys.com

The output of this program is:


5.100000 > 5

The integer constant 5 on line 7 is converted to a double and compared with dnum. The
comparison returns the integer 1 for true, which is then compared for equality with the integer
1. This is a convoluted example just to show comparison of different types and that the
relational operators return an integer result. Line 7 could have been written simply as if
( dnum > 5 ).

C Programming - Decision Making - Looping


Author: Exforsys Inc.

Published on: 4th Apr 2006

| Last Updated on: 21st Sep 2011

Loops are group of instructions executed repeatedly while certain condition remains true.
There are two types of loops, counter controlled and sentinel controlled loops (repetition).
Counter controlled repetitions are the loops which the number of repetitions needed for the
loop is known before the loop begins; these loops have control variables to count repetitions.
Counter controlled repetitions need initialized control variable (loop counter), an increment
(or decrement) statement and a condition used to terminate the loop (continuation condition).
Sentinel controlled repetitions are the loops with an indefinite repetitions; this type of loops
use sentinel value to indicate end of iteration.
Loops are mostly used to output the data stored in arrays, however they are also used for
sorting and searching of data.

For Loop
For loops is a counter controlled repetition; therefore the number iterations must be known
before the loop starts.
Sample Code
1. for(control-variable; continuation-condition;increment/decrement-control) {
2. code to iterate
3. }
Copyright exforsys.com

Hint: if the code to iterate is only a single line then the braces ({ }) can be ignored.
Diagram 1 illustrates for statement operation.

Diagram SEQ Diagram * ARABIC 1 for statement


Example: consider the case of repeating the same line of code for 10 times. We write the
code below.
Sample Code
1. int counter;
2.

for(counter=1; counter<=10; counter++)

3.

printf("n Number: %d",counter);


Copyright exforsys.com

Figure 1 simple program counting from 1 to 10


Description: statement 1 declares the control variable of this for loop. Statement 2 is
the most important part of this code. It initializes the control variable; it sets the continuation
condition and it increments the control variable after every successful iteration. Diagram 2
clearly shows how this code works.

Diagram 2 code 1's operation

The While Statement


while statement is a sentinel controlled repetition which can be iterated indefinite number
of times. Number of iterations is controlled using a sentinel variable (test expression).
Sample Code
1. while(test-expression)
2. {
3. code to execute
4. }
Copyright exforsys.com

Hint: test-expression must be initialized otherwise errors will be generated when trying to
compile the code.
Diagram 3 illustrates how while statement operates

Diagram 3 while statement


Hint: sentinel variable (test expression) must be controlled within the while statement,
otherwise the loop will run forever.
Example: here we will consider the same example as we did for for loop; this is to see how
two loops differ from each other.
Sample Code
1. int counter=1;
2. while(counter <=10)
3. {
4. printf("n Number: %d",counter);
5. counter++;
6. }
Copyright exforsys.com

Figure 2 counting from 1 to 10 using while loop


Description: this code does the same job as the code 1 but using while statement instead of
for statement.

The do..while statement


do..while statement is a sentinel controlled repetition which is quite different from the other
two statements we covered earlier. This statement runs the code first and then checks the testexpression, so there is always a guarantee that the code runs at least once. This type of loop is
generally used for password checks and menus.
Sample Code
1. do{
2. code to iterate

3. }while(test-expression)
Copyright exforsys.com

Hint: you must initialize the test-expression to avoid possible errors.


Diagram 4 illustrates the operation of do..while statement.

Diagram 4 do..while statement


Example #4: here we will consider a simple menu using do..while this code will repeat the
menu until 0 is inputted.
Sample Code
1. int input;
2. do
3. {
4. printf("n press 1 to print "hello" or 0 to exit : ");
5. scanf("%d",&input);
6. switch(input)
7. {
8. case 1: printf("hello"); break;
9. case 0: printf("exitting");break;
10. }

11. }
12. while(input !=0);
Copyright exforsys.com

Figure 3 simple menu


Description: switch statement is used to create a simple menu which allows actions for two
different cases. If and input is 0 then the while loop will be terminated once the testexpression is reached causing the program to exit.

The Break Statement


break statement is used to exit the iteration. This statement is usually used when early
escape from the loop is acceptable by the programmer. For example if we are searching for a
data, we can use break as soon as we find the data to exit the loop. You can simply use
break by writing break; at the point where you want to escape the loop. break can be
used with all the statements we have covered in this tutorial.
Diagram 5 shows how the program flow changes by break statement.

Diagram 5 use of "break"


Example: in this example, we will write a program which will escape the loop using break
as soon as the number is equal to 2.

Sample Code
1. int counter;
2. for(counter=1;counter<=10;counter++)
3. {
4. printf("nnumber: %d before break",counter);
5. if(counter==2)
6.

break;

7.

printf("nnumber: %d after break",counter);

8. }
9. printf("nloop was escaped at %d",counter);
Copyright exforsys.com

Figure 4 use of "break"


Description: counter value is initialized to 1. Therefore statements 1 and 2 will all be
executed in the first iteration, but when the counter is incremented; statement 1,2 and 4
will be executed because statement 2 will escape out of the loop and go to the first line
after the loop.

The Continue Statement


continue statement is used to skip the remaining code of the loop and start the new one.
This statement can be implemented by continue;.
Diagram 6 shows the flow of the loop.

Diagram 6 "continue" statement


Example: we will consider the case in which the loop will skip all the even numbers between
1 and 10.
Sample Code
1. int counter;
2. for(counter=1;counter<=10;counter++)
3. {
4. if(counter%2==0)
5. continue;
6. printf("nnumber: %d was not skipped",counter);
7.
8. }
Copyright exforsys.com

C Programming - Pointers
Author: Brian Moriya
25th Mar 2011

Published on: 25th May 2006

| Last Updated on:

Pointers are widely used in programming; they are used to refer to memory location of
another variable without using variable identifier itself. They are mainly used in linked lists
and call by reference functions.
Diagram 1 illustrates the idea of pointers. As you can see below; Yptr is pointing to memory
address 100.

Diagram 1: 1. Pointer and memory relationship


Pointer Declaration

Declaring pointers can be very confusing and difficult at times (working with structures and
pointer to pointers). To declare pointer variable we need to use * operator
(indirection/dereferencing operator) before the variable identifier and after data type. Pointer
can only point to variable of the same data type.
Syntax
Sample Code
1. Datatype * identifier;
Copyright exforsys.com

Example

Character Pointer
Sample Code
1. #include <stdio.h>
2. int main()
3. {
4. char a='b';
5. char *ptr;
6. printf("%cn",a);
7. ptr=&a;
8. printf("%pn",ptr);
9. *ptr='d';
10. printf("%cn",a);
11. return 0;
12. }
Copyright exforsys.com

Output

Figure 1 - Code Result

Description of code: In line 1 we are declaring char variable called a; it is initialized to


character b, in line 2, the pointer variable ptr is declared. In line 4, the address of variable a
is assigned to variable ptr. In line 6 value stored at the memory address that ptr points to is
changed to d
Note: & notation means address-of operand in this case &a means address-of a.
Address operator

Address operator (&) is used to get the address of the operand. For example if variable x is
stored at location 100 of memory; &x will return 100.
This operator is used to assign value to the pointer variable. It is important to remember that
you MUST NOT use this operator for arrays, no matter what data type the array is holding.
This is because array identifier (name) is pointer variable itself. When we call for ArrayA[2];
ArrayA returns the address of first item in that array so ArrayA[2] is the same as saying
ArrayA+=2; and will return the third item in that array.
Pointer arithmetic

Pointers can be added and subtracted. However pointer arithmetic is quite meaningless unless
performed on arrays. Addition and subtraction are mainly for moving forward and backward
in an array.
Note: you have to be very careful NOT to exceed the array elements when you use arithmetic;
otherwise you will get horrible errors such as access violation. This error is caused because
your code is trying to access a memory location which is registered to another program.

Operator

Result

++

Goes to the next memory location that the pointer is pointing


to.

--

Goes to the previous memory location that the pointer is


pointing to.

-= or -

Subtracts value from pointer.

+= or +

Adding to the pointer

Example:

Array and pointer arithmetic

Sample Code
1. #include <stdio.h>
2. int main()
3. {
4. int ArrayA[3]={1,2,3};
5. int *ptr;
6. ptr=ArrayA;
7. printf("address: %p - array value:%d n",ptr,*ptr);
8. ptr++;
9. printf("address: %p - array value:%d n",ptr,*ptr);

10. return 0;
11. }
Copyright exforsys.com

Output

Figure 2 Code 2 result


Description of code 2: in line 1 we are declaring ArrayA integer array variable initialized
to numbers 1,2,3, in line 2, the pointer variable ptr is declared. In line 3, the address of
variable ArrayA is assigned to variable ptr. In line 5 ptr is incremented by 1.

Note: & notation should not be used with arrays because arrays identifier is pointer to the
first element of the array.
Pointers and functions

Pointers can be used with functions. The main use of pointers is call by reference functions.
Call by reference function is a type of function that has pointer/s (reference) as parameters to
that function. All calculation of that function will be directly performed on referred variables.
Sample Code
1. #include <stdio.h>
2. void DoubleIt(int *num)
3. {
4.

*num*=2;

5. }
6. int main()
7. {
8.

int number=2;

9.
10.

DoubleIt(&number);
printf("%d",number);

11. return 0;
12. }
Copyright exforsys.com

Output

Figure 3 code 3 result


Description of code 3: in line 1 we are declaring DoubleIt function, in line 4, the variable
number is declared and initialized to 2. In line 5, the function DoubleIt is called.
Pointer to Arrays

Array identifier is a pointer itself. Therefore & notation shouldnt be used with arrays. The
example of this can be found at code 3. When working with arrays and pointers always
remember the following:

Never use & for pointer variable pointing to an array.

When passing array to function you dont need * for your declaration.

Be VERY CAREFUL not to exceed number of elements your array holds


when using pointer arithmetic to avoid errors.

Pointers and Structures

Pointers and structures is broad topic and it can be very complex to include it all in one single
tutorial. However pointers and structures are great combinations; linked lists, stacks, queues
and etc are all developed using pointers and structures in advanced systems.
Example:

Number Structure
Sample Code
1. #include <stdio.h>
2.

3. struct details {
4. int num;
5. };
6.
7. int main()
8. {
9.
10. struct details MainDetails;
11. struct details *structptr;
12. structptr=&MainDetails;
13. structptr->num=20;
14. printf("n%d",MainDetails.num);
15.
16.
17. return 0;
18. }
Copyright exforsys.com

Output

Figure 4. code 4 result


Description of code 4: in line 1-3 we are declaring details structure, in line 4, the variable
Maindetails is declared.in line 6, pointer is set to point to MainDetails. In line 7, 20 is
assigned to MainDetails.num through structptr->num.
Pointer to Pointer

Pointers can point to other pointers; there is no limit whatsoever on how many pointer to
pointer links you can have in your program. It is entirely up to you and your programming
skills to decide how far you can go before you get confused with the links. Here we will only
look at simple pointer to pointer link. Pointing to pointer can be done exactly in the same way
as normal pointer. Diagram below can help you understand pointer to pointer relationship.

Diagram 2. Simple pointer to pointer relationship


Code for diagram 2:
Char *ptrA;
Char x=b;
Char *ptrb;
ptrb=&x;
ptrA=&ptrb;
ptrA gives 100, *ptrA gives 101 , ptrb is 101 ,*ptrb gives b, **ptrA gives b
comment: **ptrA means value stored at memory location of value stored in memory location
stored at PtrA
Read Next: C Programming - Dynamic Memory allocation

You might also like