Sunteți pe pagina 1din 25

ARRAYS AND POINTERS

Prepared by

S.GUNASEKARAN
9/6/2011

[Type the abstract of the document here. The abstract is typically a short summary of the contents of the document. Type the abstract of the document here. The abstract is typically a short summary of the contents of the document.]

# 2 of 25

ARRAY:
An array is a list of more than one variable having same name and same data type. All array subscripts begin with 0

Processing an Array:
Single operations involving entire arrays are not permitted in C. Suppose if a and b are two similar arrays of the same data type, same dimensions and same size then assignment operations and comparison operations etc, must be carried out on an element by element basis. This is done within a loop, where each pass through the loop is used to process an element of the array. The number of passes through the loop will there for equal to the number of array elements to be processed and the value of the index (subscript) would be incremented from 0 to n-1.

One dimensional array


Syntax: Data type- variable name[]; Example: Declaration and initialization of integer array int a[]; int a[3]; int a[3] = { 1, 2, 3}; //Program for one array #include<stdio.h> #include<conio.h> #define SIZE 5 void main() { int arr[SIZE],i; clrscr(); printf("Enter 5 integers \n\n"); /*Input the 5 integers into array "arr" */ for(i=0;i<SIZE;i++) { printf("Enter integer # %d:", i+1); scanf("%d", &arr[i]); } /* print out the integers stored in array arr */ for(i=0;i<5;i++) { printf("\n Integer # %d: %d \n", i+1,arr[i]); /* i+1 is used because the C subscripts stats from 0 */ } getch(); }

# 3 of 25

Output

Multidimensional array
Declaration and initialization:
Syntax: Datatype variable name *+*+n; Example: int a[3][3]; int a[3][2]; int a[][]; int a[2][]; int a[][3]; int a[3][4] = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12} };

# 4 of 25 // Program for matrix addition #include<stdio.h> #include<conio.h> #define SIZE 5 void main() { int i,j,m,n,a[SIZE][SIZE],b[SIZE][SIZE],sum[SIZE][SIZE]; clrscr(); printf("Enter the Matrix Order"); scanf("%d%d",&m,&n); printf("Enter the Matrix A:\n"); for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%d",&a[i][j]); printf("Enter the Matrix B:\n"); for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%d",&b[i][j]); for(i=0;i<m;i++) for(j=0;j<n;j++) sum[i][j]=0; for(i=0;i<m;i++) for(j=0;j<n;j++) sum[i][j]=a[i][j]+b[i][j]; printf("The sum of matrix A & B:\n"); for(i=0;i<m;i++) {

# 5 of 25 for(j=0;j<n;j++) printf("%5d",sum[i][j]); printf("\n"); } getch(); }

OUTPUT

Passing array as argument to functions


An entire array can be passed to a function as an argument. to pass an array to a function, the array name must appear by itself, without brackets or subscripts, as an actual argument within the function call. Example: void disp(int a[2]); void main() { int a[2] = { 2, 3 }; disp(a); }

# 6 of 25 //Passing array as argument to functions: #include<stdio.h> #include<conio.h> void display(int arr[3]); void main() { int arr[3]; int i; clrscr(); for(i=1;i<=3;i++) { printf(\nEnter the number %d:,i); scanf(%d,&arr*i+); } display(arr); /* pass array as argument to function*/ getch(); } void display(int arr[3]) { int i; for(i=1;i<=3;i++) printf(\n\n Element in array*%d+ is: %d, I,arr*i+); }

# 7 of 25

OUTPUT

ARRAYS AND STRINGS


Introduction
A group of characters can be stored in a character array similar to that of integer array. Character arrays are called as Strings. A string constant is one dimensional array of characters terminated by a null character (\0) example, char initials*5+=,I ,n , d , I , a-; It is only access individual character elements not string because of not end in null zero Printf(%c %c,a*0+,a[2]); //print the output is i and d If you want store the character name ,just like declare the following method. char name*+=india; Same as char name*6+=india; If you access the individual character like this Printf(%c %c,a*0+,a[2]); //print the output is i and d If you access all the character or string like this

# 8 of 25 Printf(%s,name); // pirnt the output is india char name*3+*10+=,India , Tamilnadu ,Trichy-; Same as char name*+*+=,India , Tamilnadu ,Trichy-; scanf(%s,name) Here & symbol missing in scanf function. It doesnt provide any error. Because we are passing base address (name) in scanf which is itself an address and & is not necessary in scanf() function.

Standard Library String Functions


The following are the standard string functions which is present in the string.h header file. strlen Find the length of the string. strcat Append one string at the end of another i.e. concatenation of string. strncat Append first n characters of a string at the end of another. strcmp Compare two strings. strncmp Compares first n character of one string to another. strcpy Copies a string into another. strncpy Copies first n characters of one string to another. strrev Reverse a string. strdup Duplicates a string. strchr Finds last occurrence of a given string character in a string. strstr finds first occurrence of a given string character in another string. strlwr Converts a string to lowercase. strupr Converts a string to uppercase. Out of the above listed functions we discuss some of the following:

# 9 of 25

strlen

strcpy

String Functions

strcat

strcmp

strlen() function:
This function counts the number of characters present in a string. Consider the following example: //Program for strlen() function #include<stdio.h> #include<conio.h> #include<string.h> void main() { char name[]="C PROGRAMMING"; char name1[]="GOVERNMENT COLLEGE OF TECHNOLOGY"; int len,len2; clrscr(); len=strlen(name); len2=strlen(name1); printf("****OUTPUT****"); printf("\nname=%d",len); printf("\nname1=%d",len2); getch(); }

# 10 of 25

OUTPUT

Here it count only the string and not count\0. The length of the string is computed even when there is a blank space in the string.

Strcpy() function
This function copies the contents of one string into another. The base address of the source and target strings should be supplied to this function. It is the users responsibility to see the target strings dimension is large enough to hold the string being copied into it. Consider the Example, //Program for Strcpy() function #include<stdio.h> #include<conio.h> #include<string.h> void main() { char source*+=C is a powerful language; char target[30]; clrscr();

# 11 of 25 strcpy(target,source); printf("****OUTPUT****"); printf(\nSource=%s,source); printf(\nTarget=%s,target); getch(); }

OUTPUT

strcat() function
This function concatenates or combines the source string at the end of target string. The target string should have the sufficient storage to hold the final string. Example: //Program for strcat() function #include<stdio.h> #include<conio.h> #include<string.h> void main() { char source[]="string";

# 12 of 25 char target[35]="concatenation.."; clrscr(); strcat(target,source); printf("****OUTPUT****"); printf("\nSource=%s",source); printf("\nTarget=%s",target); getch(); }

OUTPUT

strcmp() function
This is a function which compares two string to find out whether they are same or not. The two strings are compared character by character until there is a mismatch or end of the strings is reached, whichever occurs first. If the two strings are identical, strcmp() returns a value zero else it returns the numeric difference between ascii values of the non matching characters. Program: #include<stdio.h> #include<conio.h> #include<string.h>

# 13 of 25 void main() { char string1*+=Jerry; char string2*+=Ferry; int i,j; clrscr(); i=strcmp(string1,Jerry); j=strcmp(string1,string2); printf("****OUTPUT****"); printf(\ni=%d j=%d,i,j); getch(); }

OUTPUT

POINTER
Pointer is a derived data type in C .Pointer is a variable that holds the address of another variable (regular variable)

# 14 of 25

Advantage of pointer variable


Pointers are more efficient in handling arrays and data types Pointer can be used to return multiple values from a function via function arguments Pointers allow C to support dynamic memory management Pointer provide an efficient tool for manipulating dynamic data structure such as structure, linked list, queues, stack and trees Pointer reduce the length and complexity of programs They increase the execution speed and thus reduce the program execution time

They are two operators which is used to pointer


The address of (&) operator The dereferencing (*) operator

Rules of pointer
Must declare the pointer variable before to use They is a type of pointer for every data type in C such as integer pointer, floating pointer, and so on You can declare global pointer or local pointer, depending on where you declare them The (*) dereferencing operator must put before pointer variable in declaration part

Declaring pointer variable


int age=10 // the regular variable age holds the value

int *page; //this is pointer variable page=&age; //the pointer variable holds the address of regular variable its same as int age=10,*page=&age; Example // simple program for pointer #include<stdio.h> #include<conio.h> void main() { int x,*px; clrscr(); printf("Enter the value: "); scanf("%d",&x);

# 15 of 25 px=&x; printf("\nThe regular variable holds the value: %d",x); //print the regular variable value printf("\nThe Regular variable address is: %d",&x); //print the regular variable address printf("\nThe Pointer variable point the value: %d",*px); //print the regular variable value printf("\nThe Pointer variable holds the address of regular variable: %d",px); //print the regular variable address printf("\nThe pointer variable address is: %d",&px); //print the pointer variable address getch(); }

OUTPUT

PASSING POINTER TO FUNCTION


Passing pointer is nothing but which pass the address by regular variable to called function Example //Program for swapping to using pointer and pass the address to function #include<stdio.h> #include<conio.h> void swap(int *,int *); // Function Prototye void main() {

# 16 of 25 int i,j; // Regular variable declaration clrscr(); printf("\tEnter the Two values:"); scanf("%d %d",&i,&j); printf("\t*******OUT PUT*******"); printf("\t\n\nBefore swap i=%d and j=%d\n\n",i,j); swap(&i,&j); //Pass the Address to Function printf("\t\n\n After swap i=%d and j=%d \n\n", i,j); getch(); } void swap(int *x,int *y) //called function { int temp; temp=*x; *x=*y; *y=temp; }

OUTPUT

# 17 of 25

OPERATION ON POINTERS
Store the string in pointer array must be declare like this
Declare the single dimensional character array Each pointer points to a string in memory and strings do not have to be the same length Definition for such an array Char *name*5+=,,SURESH-,,KUMAR-,,SAKTHI-,,MADHU--

Example //simple program for two dimensional arrays #include<stdio.h> #include<conio.h> void main() { char *name[5]={"India","Tamilnadu","Trichy","Thuraiyur","Uppiliapuram"}; int i; clrscr(); printf("*****Print the name in output screen*****\n"); for(i=0;i<5;i++) { printf("%s",*(name+i)); //display the name in output screen printf("\n"); } getch(); }

# 18 of 25

OUTPUT

Array value can be represented in 4 ways by using the pointer


Example: name[i]; *(name+i); *(i+name); i[name]; Program: #include<stdio.h> #include<conio.h> void main() { int i; char a*4+=man; clrscr(); printf("****OUTPUT****");

# 19 of 25 for(i=0;i<3;i++) printf(\n%c %c %c %c, *(a+i),a*i+,*(i+a),i*a+); getch(); } Output:

POINTER AND ARRAYS


Pointer and one dimensional array
Programmers use pointers rather than arrays because arrays are easy to declare .sometimes declare the arrays and then use pointers to reference those array. If the array data changes the pointer helps to change it //simple program for one dimensional array using pointer #include<stdio.h> #include<conio.h> void main() { int i,n,a[10],*p; //declare local variable clrscr(); printf("How many elemnts you enter(1-10)"); scanf("%d",&n);

# 20 of 25 printf("Enter the value"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } p=a; printf("Using array Subcripts\n"); printf("a\t p\n"); for(i=0;i<n;i++) { printf("%d\t%d\n",a[i],p[i]); } printf("\nUsing pointer notation\n"); printf("a\t p\n"); for(i=0;i<n;i++) { printf("%d\t%d\n",*(a+i),*(p+i)); } getch(); }

# 21 of 25

OUTPUT

Using character pointer


If you can store the strings in character array to point them with character pointer. Two methods for string char a*+= C is fun; char *p=C is fun; both strings are print the following method printf(%s,a); //array string printf(%s,p); //pointer string The main advantage in pointer are, suppose you add another string you cant add array like this a=Hello //invalid but pointer can do the work p=Hello //valid Example // Changing character string #include<stdio.h> #include<conio.h> void main() {

# 22 of 25 char *c= " C is a Easy Language"; clrscr(); printf(" %s\n",c); c="It is also Difficult if you not understand"; //assigns new value printf("%s\n",c); getch(); }

OUTPUT

ARRAYS OF POINTERS
Pointers arrays that is, arrays whose elements have a pointer type are often a handy alternative to two-dimensional arrays. Usually the pointers in such an array point to dynamically allocated memory blocks. For example, if you want to process strings, you could store them in a two-dimensional array whose row size is large enough to hold the longest string that can occur:
#define ARRAY_LEN 100 #define STRLEN_MAX 256 char myStrings[ARRAY_LEN][STRLEN_MAX] = { "If anything can go wrong, it will.",

# 23 of 25
"Nothing is foolproof, because fools are so ingenious.", "Every solution breeds new problems." };

However, this technique wastes memory, as only a small fraction of the 25,600 bytes devoted to the array is actually used. For one thing, a short string leaves most of a row empty; for another, memory is reserved for whole rows that may never be used. A simple solution in such cases is to use an array of pointers that reference the objects in this case, the strings and to allocate memory only for the pointer array and for objects that actually exist. Unused array elements are null pointers.
#define ARRAY_LEN 100 char *myStrPtr[ARRAY_LEN] = // Array of pointers to char { // Several corollaries of Murphy's Law: "If anything can go wrong, it will.", "Nothing is foolproof, because fools are so ingenious.", "Every solution breeds new problems."

}; mystrptr[0] mystrptr[1] mystrptr[2] mystrptr[3] . . . . mystrptr[99] If anything can go wrong, it will. Nothing is foolproof, because fools are so ingenious. Every solution breeds new problems.

FUNCTION TO OTHER FUNCTION


/*Program for function to other function */ #include<stdio.h> #include<conio.h> void main() { int f; clrscr(); f=addone(10,11); // calling function f=f/10; printf("\nThe squared value divided: %d",f); getch();

# 24 of 25 } int addone(int a,int b) //called function { int c,e; c=a+b; e=addtwo(c); //calling function return e; } int addtwo(int a) //called function { int d; d=a*a; printf("\nThe squared value is %d",d); return d; }

OUTPUT

# 25 of 25

In the main(), the addone() calling functions are passed two values as argument to the called function. The called function addone() ,add the two values and store the resultant value to the another variable. The resultant stored value are passed as a arguments in another function addtwo(). In the addtwo () function to square the value then return the value to main() function .In the main() function divide the return value and then print the output screen

S-ar putea să vă placă și