0% found this document useful (0 votes)
115 views19 pages

C Programming: Arrays and Strings Guide

The document covers concepts related to strings and pointers in C programming, including one-dimensional and multi-dimensional arrays, their declarations, initializations, and operations. It also discusses string handling functions and pointer arithmetic, along with practical examples and code snippets. Key topics include array access, string manipulation functions, and pointer usage in memory management.

Uploaded by

Satheesh Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
115 views19 pages

C Programming: Arrays and Strings Guide

The document covers concepts related to strings and pointers in C programming, including one-dimensional and multi-dimensional arrays, their declarations, initializations, and operations. It also discusses string handling functions and pointer arithmetic, along with practical examples and code snippets. Key topics include array access, string manipulation functions, and pointer usage in memory management.

Uploaded by

Satheesh Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UCE- Nagercoil

Module – 4

Strings & Pointers: One-dimensional and Multi-dimensional Arrays, Array operations and
traversals, String Handling: String declaration, input/output, string library functions, Pointer
arithmetic, Pointers and Arrays, Pointers to function, Dynamic memory allocation.

Practical: Programs using pointers, dynamic memory, pointer arithmetic, string manipulations,
array operations. (Minimum three)

ONE DIMENSIONAL ARRAYS:


Array is a collection of similar (homogeneous) data elements stored in consecutive memory
location. Array elements are accessed or referred by an index also known as subscript.

Advantage of C Array:
 Optimal Code.
 Easy traversal of data
 Random Access by its index.

Disadvantage of C Array:
Fixed Size: Size of the array is static, it is fixed at the time of declaration itself.

Array Declaration:
Syntax:
data_type array_name[size];

Ex: int marks[10];


Memory representation of the above code is

The following declarations are illegal in C.

CS25C01 Computer Programming: C Page 1


UCE- Nagercoil

int arr[]; // array size should be mentioned.


int arr[n]; // array size should be fixed.

Accessing the element of an array :


Array subscript or index is used to access elements of an array.
Calculating the address of an array element

Address of an element A[k] at index k = Base address of A + word size of one element * (k-lower
bound).

Calculating the length of an array:


Length = upper_bound – lower_bound +1

CS25C01 Computer Programming: C Page 2


UCE- Nagercoil

Storing values in array


Values can be stored in an array in three ways:
 Initialization during declaration
 Input through keyboard
 Assign value to individual elements
Initialization during declaration:
Syntax: data_type array_name[size] = { list of value };
Ex: int marks[5] = {90, 85, 95, 99, 89};
While initializing the values during declaration the size of the array may also be omitted.
int marks[] = {90, 85, 95, 99, 89};

Input through keyboard:


Array elements can be filled by inputting values from keyboard using looping statements(for,
while or do_while loop).
#include<stdio.h>
int main()
{
int i=0,int marks[5];
for(i=0;i<5;i++)
{
scanf("%d",&marks[i]);
}
}
Assign value to individual elements:

CS25C01 Computer Programming: C Page 3


UCE- Nagercoil

Subscript starts with 0, which means arr[0] represents the first element in the array arr.
In general arr[n-1] can be used to access nth element of an array. where n is any integer number.

Initialization of C Array:
A simple way to initialize array is by index. Notice that array index starts from 0 and ends with
[SIZE - 1].
marks[0]=80;//initialization of array marks[1]=60;
marks[2]=70; marks[3]=85; marks[4]=75;

Example:
#include<stdio.h>
int main()
{ Output:
int i=0; 80
int marks[5];//declaration of array 60
marks[0]=80;//initialization of array 70
marks[1]=60; 85
marks[2]=70; marks[3]=85; 75

marks[4]=75;
//traversal of array

for(i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}//end of for loop return 0;
}

C Array: Declaration with Initialization:

We can initialize the c array at the time of declaration. Let's see the code. int marks[5]={20,30,40,50,60};

In such case, there is no requirement to define size. So it can also be written as the following code.

CS25C01 Computer Programming: C Page 4


UCE- Nagercoil

Example: int marks[]={20,30,40,50,60};

Programs:
#include<stdio.h>
int main()
{
int i=0;
int marks[5]={20,30,40,50,60};//declaration and initialization of array
//traversal of array for(i=0;i<5;i++)
{ Output:
printf("%d \n",marks[i]);
} 20
return 0; 30
} 40
50
Program to search an element in array: 60
#include <stdio.h>
int main() {
int arr[] = {10, 50, 30, 70, 80, 60, 20, 90, 40};
int n = sizeof(arr) / sizeof(arr[0]);
int key;
int found_index = -1;

printf("Enter the element to search: ");


scanf("%d", &key);

// Perform linear search


for (int i = 0; i < n; i++) {
if (arr[i] == key) {
found_index = i; // Element found, store its index
break; // Exit the loop as the element is found
}
}

// Print the result


if (found_index != -1) {
printf("Element %d found at index %d.\n", key, found_index);
} else {
printf("Element %d not found in the array.\n", key);
}
return 0;
}

TWO DIMENSIONAL ARRAYS (2 D arrays):

CS25C01 Computer Programming: C Page 5


UCE- Nagercoil

The two dimensional array in C language is represented in the form of rows and columns, also
known as matrix. It is also known as array of arrays or list of arrays.
The two dimensional, three dimensional or other dimensional arrays are also known as
multidimensional arrays.
Declaration of two dimensional Array in C:
We can declare an array in the c language in the following way.
Syntax:
data_type array_name[size1][size2];
A simple example to declare two dimensional array is given below.
Example: int twodimen[4][3];
Here, 4 is the row number and 3 is the column number.
Initialization of 2D Array in C:
A way to initialize the two dimensional array at the time of declaration is given below.
Example: int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Output:
Programs:
arr[0][0] = 1
#include<stdio.h> arr[0][1] = 2
int main() arr[0][2] = 3
{ arr[1][0] = 2
int i=0,j=0; arr[1][1] = 3
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}}; arr[1][2] = 4
//traversing 2D array arr[2][0] = 3
for(i=0;i<4;i++) arr[2][1] = 4
{ arr[2][2] = 5
for(j=0;j<3;j++) arr[3][0] = 4
{ arr[3][1] = 5
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]); arr[3][2] = 6
}//end of j
}//end of i
return 0;
}

Multiplication of two numbers in array:


#include<stdio.h>
#include<stdlib.h>
int main()
{

CS25C01 Computer Programming: C Page 6


UCE- Nagercoil

int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
printf("enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
} Output:
printf("enter the second matrix element=\n");
for(i=0;i<r;i++) enter the number of row=3
{ enter the number of column=3
for(j=0;j<c;j++) enter the first matrix element=
{ 111
scanf("%d",&b[i][j]); 222
} 333
} enter the second matrix element=
111
printf("multiply of the matrix=\n"); 222
for(i=0;i<r;i++) 333
{ multiply of the matrix=
for(j=0;j<c;j++) 666
{ 12 12 12
mul[i][j]=0; 18 18 18
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
//for printing result
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
}
STRING:

CS25C01 Computer Programming: C Page 7


UCE- Nagercoil

String is an array of characters that is terminated by \0 (null character).


There are two ways to declare string in c language.
 By char array
 By string literal
Declaring string by char array :
char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};

Define string by string literal:


Example: char ch[]="javatpoint";
In such case, '\0' will be appended at the end of string by the compiler.

Difference between char array and string literal:


The only difference is that string literal cannot be changed whereas string declared by char array
can be changed.
Programs:
Example to declare and print string. The '%s' is used to print string in c language.
#include<stdio.h> Output:
#include <string.h>
int main() Char Array Value is: welcome
{ String Literal Value is: welcome
char ch[8]={'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0'};
char ch1[8]="welcome";
printf("Char Array Value is: %s\n", ch);
printf("String Literal Value is: %s\n", ch1);
return 0;
}

String operations: length-strlen()


The strlen() function returns the length of the given string. It doesn't count null character '\0'.
Example:
#include<stdio.h>
#include <string.h>
int main()
{
Output:
CS25C01 Computer Programming: C Page 8 Length of string is: 8
UCE- Nagercoil

char ch[10]={'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0'};


printf("Length of string is: %d",strlen(ch));
return 0;
}

String operations: compare-strcmp():


The strcmp(first_string, second_string) function compares two string and returns 0 if both strings
are equal.
Here, we are using gets() function which reads string from the console.
Programs:
#include<stdio.h>
#include <string.h> Output:
int main()
{ Enter 1st string: hello
char str1[20],str2[20]; Enter 2nd string:
printf("Enter 1st string: "); hello Strings are
gets(str1); equal
printf("Enter 2nd string: ");
gets(str2);
if( (strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}

String operations: concatenate-strcat():


The strcat(first_string, second_string) function concatenates two strings and result is returned to
first_string.
Programs:
#include<stdio.h>
#include <string.h>
int main()
{ Output:
char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
char ch2[10]={ 'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0'}; Value of first string is: hellowelcome
strcat(ch,ch2);
printf("Value of first string is: %s",ch);
return 0;
}
String operations: copy-strcpy():
The strcpy(destination, source) function copies the source string in destination

CS25C01 Computer Programming: C Page 9


UCE- Nagercoil

Programs:
#include<stdio.h>
#include <string.h> Output:
int main()
Value of second string is: welcome
{
char ch[20]={ 'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0'};
char ch2[20];
strcpy(ch2,ch);
printf("Value of second string is: %s",ch2);
return 0;
}
String operations:Reverse - strrev():
The strrev(string) function returns reverse of the given string. Let's see a simple example of
strrev() function.
Programs:
#include<stdio.h>
#include <string.h>
int main()
Output:
{
char str[20]; Enter string: welcome
printf("Enter string: ");
gets(str); String is: welcome
printf("String is: %s",str); Reverse String is:
printf("\nReverse String is: %s",strrev(str)); emocelew
return 0;
}

String operation: lower- strlwr():


The strlwr(string) function returns string characters in lowercase. Let's see asimple example of
strlwr() function.
Programs:
#include<stdio.h> Output:
#include <string.h>
int main() Enter string: WELCOME
{ String is: WELCOME
char str[20]; printf("Enter string: "); Lower String is: welcome
gets(str);
printf("String is: %s",str);
printf("\nLower String is: %s",strlwr(str));
return 0;
}
String operation:upper-strupr():

CS25C01 Computer Programming: C Page 10


UCE- Nagercoil

The strupr(string) function returns string characters in uppercase. Let's see a simple example of
strupr() function.
Programs:
#include<stdio.h> Output:
#include <string.h> Enter string: welcome
int main() String is: welcome
{ Upper String is: Welcome
char str[20];
printf("Enter string: ");
gets(str);
printf("String is: %s",str);
printf("\nUpper String is: %s",strupr(str));
return 0;
}

POINTERS
A pointer is a variable that contains the memory location of another variable.
Declaring Pointer Variables
The general syntax of declaring pointer variables can be given as below
data type *ptr name;
Here, data type is the data type of the value that the pointer will point to.
For example,
int x =10
int *ptr;
ptr=&x

ex: program using pointer


#include<stdio.h>
int main()
{
int num,*pnum;
pnum=&num;
printf(“enter the number”);
scanf(“%d”,&num);
printf(“the no that was entered is %d”,*pnum);
return 0;
}
Output
Enter the number : 10
The number that was entered is : 10

CS25C01 Computer Programming: C Page 11


UCE- Nagercoil

The Pointer Operators:


There are two pointer operators :
value at address operator ( * )
address of operator ( & )
Value at address operator ( * )
The * is a unary operator. It gives the value stored at a particular address. The ‘value at address’
operator is also called ‘indirection’ or dereference operator.

Address of operator ( & )


The & is a unary operator that returns the memory address of its operand

Output of the program :


Address of a = 12345
Address of a = 12345
Address of b = 12348
Value of b = 12345
Value of a = 5

Value of a = 5
Value of a = 5

Pointer Arithmetic
There are four arithmetic operators that can be used on pointers: ++, --, +, and –
Valid Pointer Arithmetic Operations
 Adding a number to pointer.
 Subtracting a number form a pointer.
 Incrementing a pointer.
 Decrementing a pointer.

CS25C01 Computer Programming: C Page 12


UCE- Nagercoil

 Subtracting two pointers.

Invalid Pointer Arithmetic Operations


 Addition of two pointers.
 Division of two pointers.

#include <stdio.h>
int main()
{
int m = 5, n = 10, q = 0;
int *p1;
int *p2;
int *p3;
p1 = &m;
p2 = &n;
printf("p1 = %d\n", p1);
printf("p2 = %d\n", p2);
q = *p1+*p2;
printf("*p1+*p2 = %d\n", q);
p3 = p1-p2;
printf("p1 - p2 = %d\n", p3);
p1++;
printf("p1++ = %d\n", p1);
p2--;
printf("p2-- = %d\n", p2);
return 0;
}
OUTPUT:
p1= 2680016
p2 = 2680012
*p1+*p2 = 15
p1-p2 = 1
p1++ = 2680020
p2-- = 2680008

//Below line will give ERROR


printf("p1+p2 = %d\n", p1+p2);

NULL POINTER
Null pointer which is a special pointer value and does not point to any value. This means that a

CS25C01 Computer Programming: C Page 13


UCE- Nagercoil

null pointer does not point to any valid memory address.


int *ptr = NULL;

#include <stdio.h> int main()


{
int *ptr = NULL;
printf("The value of ptr is %u",ptr);
return 0;
}

Output :
The value of ptr is 0

POINTERS AND ARRAYS :

Syntax:
int *ptr;
ptr = &arr[0];

Here, ptr is made to point to the first element of the array.


Eg:// program to display an array of given numbers.

#include <stdio.h>
int main()
{
int arr[]={1,2,3,4,5,6,7,8,9};
int *ptr1, *ptr2;
ptr1 = arr;
ptr2 = &arr[8];
while(ptr1<=ptr2)
{
printf("%d", *ptr1);
ptr1++;
}
return 0;
}

Output

CS25C01 Computer Programming: C Page 14


UCE- Nagercoil

1234567

ARRAY OF POINTERS:
An array of pointers can be declared as.
datatype *array_name[size];

Eg:int *ptr[10];

The above statement declares an array of 10 pointers where each of the pointer points to an
integer variable.
Example 2://Program on Array of Pointers
int main()
{
int *ptr[10];
int p = 1, q = 2, r = 3, s = 4, t = 5;
ptr[0] = &p;
ptr[1] = &q;
ptr[2] = &r;
ptr[3] = &s;
ptr[4] = &t;
printf("\n %d", *ptr[3]);
return 0;
}
OUTPUT:4

Example 2://Program on Array of Pointers


int main()
{
int arr1[]={1,2,3,4,5};
int arr2[]={0,2,4,6,8};
int arr3[]={1,3,5,7,9};
int *parr[3] = {arr1, arr2, arr3};
int i;
for(i = 0;i<3;i++)
printf(«%d», *parr[i]);
return 0;
}
Output: 1 0 1

Applications of Pointers
 Pointers are used to pass information back and forth between functions.

CS25C01 Computer Programming: C Page 15


UCE- Nagercoil

 Pointers enable the programmers to return multiple data items from a function via
function arguments.
 Pointers provide an alternate way to access the individual elements of an array.
 Pointers are used to pass arrays and strings as function arguments.
 Pointers are used to create complex data structures, such as trees, linked lists, linked
stacks,linkedqueues, and graphs.

Write a program to add two integers using pointers and functions.


#include <stdio.h>
void sum (int*, int*, int*);
int main()
{
int num1, num2, total;
printf("\n Enter the first number : ");
scanf("%d", &num1);
printf("\n Enter the second number : ");
scanf("%d", &num2);
sum(&num1, &num2, &total);
printf("\n Total = %d", total);
return 0;
}
void sum (int *a, int *b, int *t)
{
*t = *a + *b;
}
Output
Enter the first number : 23
Enter the second number : 34
Total = 57
Pointers to function:
Function pointer is a type of pointer that stores the address of a function.
Function Pointer Declaration
Syntax: return_type (*pointer_name)(parameter_types);
 return_type: The type of the value that the function returns.
 parameter_types: The types of the parameters the function takes.
 pointer_name: The name of the function pointer.
Function Pointer Initialization:

CS25C01 Computer Programming: C Page 16


UCE- Nagercoil

A function pointer is then initialized by assigning the address of the function.


Syntax: pointer_name = &function_name

Example:
#include <stdio.h>
int multiply(int a, int b)
{
return a * b;
}

int main()
{
int (*funcPtr)(int, int); // Declare a function pointer
funcPtr = &multiply; // Assign the address to funcPtr
int result = funcPtr(7, 3);
printf("Result of multiplication: %d\n", result);
return 0;
}

Output: 21

Dynamic Memory Allocation:


C supports three types of memory allocation.
 Static allocation: variables declared as static or global. Memory size cannot be altered
during execution of program.
 Automatic allocation: done when local variables are declared. Memory allocated when
the execution enters the statement block and freed when it exits from the statement block.
 Dynamic allocation: The process of allocating memory at the time of execution or run
time is called as dynamic memory allocation. C language has four library routines to
allocate memory during run time.

CS25C01 Computer Programming: C Page 17


UCE- Nagercoil

malloc(): Reserves a block of memory of specified size and returns a void pointer.
A void pointer is a pointer that can point to any data type. A void pointer can hold an address of
any type and can be typecasted to any type.
Syntax:
ptr=(cast-type*)malloc(byte-size)
where ptr is a pointer of cast-type.

Example:
a=(int*)malloc(10*sizeof(int));
The above example will dynamically allocate memory equivalent to ten times the area of integer
bytes.

calloc(): calloc stands for contiguous memory allocation, used to allocate a array of memory. It
reserves multiple blocks of storage of same size and sets all bytes to zero.
Syntax: ptr=(cast-type*)calloc(n, element-size)
where ptr is a pointer of cast-type. The above statement allocated contiguous space for n blocks
each of element-size bytes.
If the memory allocation is successful both malloc() and calloc() will return a void pointer and if
memory allocation is not successful it returns a null pointer.
Difference between malloc() and calloc():
The only difference between malloc() and calloc() is while using calloc() all the bytes are
initialized to zero.
Example:
a=(int*)malloc(10*sizeof(int));
The above example will dynamically allocate memory equivalent to ten times the area of integer
bytes.

realloc(): Alter the size of allocated memory


The memory allocated using malloc() or calloc() may be insufficient or excess in such case we
can use realloc() to change the memory size already allocated.

CS25C01 Computer Programming: C Page 18


UCE- Nagercoil

Syntax: ptr= realloc(ptr,newsize);


Allocated new memory space of specified new size to the pointer ptr. It returns a pointer to the
first byte of the memory block. Allocated memory block may or may not be same location. If the
new size is mentioned as zero, it releases the allocated memory and its equivalent to calling the
free() function.

free(): Releasing the used space

In dynamic memory allocation, if we do not need the allocated memory it needs to be de-
allocated or released explicitly. free() function is used to release the block of memory for future
use.
syntax: free(ptr);
ptr is the pointer created by using malloc() or calloc().

CS25C01 Computer Programming: C Page 19

You might also like