MODULE 4
STRINGS AND POINTERS
Strings
• A string constant or a string literal can be defined as a sequence of
characters enclosed in double quotes that will be treated as a single data
element followed by a null character ‘\0’
• Syntax: char string_name[size];
• where, char is the data type of strings
• string_name is a valid identifier which is the name for the string variable
• size indicates the length of the string which is to be stored
Initialization of strings
char str1[10]= “peter”;
or
char str1[10]={‘p’,‘e’,‘t’,‘e’,‘r’};
• Both the initializations mentioned are same if we directly specify the entire
string at a time we use “ ”
• if we specify the characters separately we should use ‘ ’, for each character
and finally enclosing all the characters within { }
• The string initialized previously will be stored in memory as
0 1 2 3 4 5 6 7 8 9
str1
p e t e r ‘\0’
Formatted input and output
• scanf() and printf():
• The scanf() and printf()statements are used when we are reading or
displaying a single string (without space).
• We do not use “&” symbol in scanf because string name itself represent the
address where it is to be stored.
%s is the format specifier used for string.
/* C program to read and display string using formatted I/O function */
#include<stdio.h>
void main() {
char str[20];
printf(“Enter a string\n”);
scanf(“%s”,str);
printf(“The entered string is=%s\n”,str);
}
Unformatted input and output
• gets() and puts(): if we want to read or display the set of strings (sentence
or words with space) we make use of gets() and puts() function for single
display at once
/* C program to read and display string using formatted I/O function */
#include<stdio.h>
void main() {
char str[20];
printf(“Enter a string\n”);
gets(str);
printf(“The entered string is\n”);
puts(str); }
Array of Strings/Multi dimensional Strings
• The two dimensional array of strings is an array of one dimensional
character array which consist of strings as its individual elements.
• Syntax:
char string_name[size1][size2];
• where, char is a datatype of strings
• string_name is a valid identifier which is the name of the string variable
• size1 indicates the number of strings in the array.
• size 2 indicates the maximum length of each string.
Static Initialization of strings
char str1[3][10]={“Thomas”,“Bob ”,“Alice”};
Dynamic Initialization of Array of strings
• /* C program for reading and displaying Array of strings */
#include<stdio.h>
void main() {
char str[50][50];
int n,i;
printf(“Enter the number of names\n”);
scanf(“%d”,&n);
printf(“Enter %d names\n”,n);
for(i=0;i<n;i++) {
scanf(“%s”,str[i]); }
printf(“Entered names are \n”);
for(i=0;i<n;i++) {
printf(“%s\n”,str[i]);
}
}
String Manipulating Functions
• C supports different string handling functions to perform different
operations on the strings.
• All the string handling functions are stored in the header file
“#include<string.h>”.
• Some of the most common used built-in string manipulation functions are
• strlen() : Returns the number of character in the given string
• strcmp() : Compares two string for their similarity
• strcpy() : Copies source string into destination string variable
• strcat() : Concatenates (joins) two string into single string
• strrev() : Reverses a given string
• strupr() : Converts characters to upper case
• strlwr() : Converts characters to lower case
• String Length : The function strlen() is used to find the length of the
string in terms of number of characters in it.
• SYNTAX: strlen(string_data);
• String taxonomy means details of different type of strings and their
manipulation.
• /* C program to find length of the string using strlen() function */
#include<stdio.h>
#include<string.h> OUTPUT
void main() { Enter a string
char str1[50]; majali
Length of the String=6
int len;
printf("Enter a string\n");
scanf("%s",str1);
len=strlen(str1);
printf("Length of the String=%d\n",len);
}
/* C program to find length of the string without using strlen function */
#include<stdio.h>
#include<string.h>
void main() {
char str1[50];
int i,count;
printf("Enter a string\n");
scanf("%s",str1);
count=0;
for(i=0;str1[i]!='\0';i++) {
count=count+1; }
printf("Length of the String=%d\n",count); }
/* C program to find length of the string with out using strlen function */
#include<stdio.h>
#include<string.h>
OUTPUT
void main() {
Enter a string
char str1[50]; Godric_Griffindor
int i,count; Length of the String=17
printf("Enter a string\n");
scanf("%s",str1);
count=0;
for(i=0;str1[i]!='\0';i++) {
count=count+1; }
printf("Length of the String=%d\n",count); }
String Compare
• The function strcmp() is used to compare the string data every character of
one string is compared with the corresponding position character of second
string.
• SYNTAX
strcmp(str1,str2);
• The function returns 0 if there is complete match (str1==str2)
• Returns positive value if str1>str2
• Returns negative value if str1<str2
/* C program to compare two strings using strcmp( ) function */
#include<stdio.h>
#include<string.h>
void main() {
char str1[20],str2[20];
int k;
printf("Enter string 1\n");
scanf("%s",str1);
printf("Enter string 2\n");
scanf("%s",str2);
k=strcmp(str1,str2);
if(k==0)
printf("Strings are same\n");
else
printf("Strings are different\n");
}
OUTPUT:
Enter string 1
geck
Enter string 2
geck
Strings are same
/* C program to compare two strings without using strcmp( ) function */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main() {
char str1[20],str2[20];
int len1,len2,i;
printf("Enter string 1\n");
scanf("%s",str1);
printf("Enter string 2\n");
scanf("%s",str2);
len1=strlen(str1);
len2=strlen(str2);
if(len1!=len2)
printf("Strings are different\n");
else {
for(i=0;str1[i]!='\0';i++) {
if(str1[i]!=str2[i]) {
printf("Strings are different\n");
exit(0); } }
printf("Strings are same\n"); } }
String Copy
• The function strcpy() copies the content from one string to another string
• SYNTAX strcpy(str2,str1);
String Concatenate
• The function strcat() is used to concatenate (attach) two strings.
• SYNTAX strcat(str1,str2);
string str2 is attached to the end of string str1
String n Concatenate
• The function strncat() is used to concatenate the specified number of
characters only
• SYNTAX strncat(string1,string2,n);
where n is an integer value which concatenates only n characters of
string2 to string1.
/* C program to illustrate strncat( ) function*/
#include<stdio.h>
#include<string.h>
void main() {
char str1[30],str2[30];
printf("Enter String1 and String2\n");
scanf("%s%s",str1,str2);
strncat(str1,str2,5);
printf("The concatenated string is=%s\n",str1);
}
Output:
Enter String1 and String2
Hermoine
Granger
The concatenated string is=HermoineGrang
String Reverse
• The function strrev() is used to reverse the string.
• The characters from left to right in the original string are placed in the
reverse order
• SYNTAX:
strrev(str1);
String Lower
• The function strlwr() converts each character of the string to lowercase.
• SYNTAX:
strlwr(string_data);
String Upper
• The function strupr() converts each character of the string to uppercase.
• SYNTAX
strupr(string_data);
Other Applications of strings
• The String functions are also used to count the number of vowels and
consonants in the given string.
• And also gives the frequency of occurrence of each vowel in the given
string.
• This program makes use of the header file “#include<ctype.h>” which is
useful for testing and mapping characters.
• We also make use of the function “isalpha()” which is used to check if the
parsed character is an alphabet or not.
What is a Pointer in C?
• A pointer is defined as a derived data type that can store the address of
other C variables or a memory location.
• We can access and manipulate the data stored in that memory location
using pointers.
Syntax of C Pointers
• The syntax of pointers is similar to the variable declaration in C, but we use
the ( * ) dereferencing operator in the pointer declaration.
• datatype * ptr;
where,
ptr is the name of the pointer.
datatype is the type of data it is pointing to.
Pointer Initialization
• Pointer initialization is the process where we assign some initial value to
the pointer variable.
• We generally use the ( & ) addressof operator to get the memory address of
a variable and then store it in the pointer variable.
int var = 10;
int * ptr;
ptr = &var;
• We can also declare and initialize the pointer in a single step. This method
is called pointer definition as the pointer is declared and initialized at the
same time.
int *ptr = &var;
Pointer Declaration
• In pointer declaration, we only declare the pointer but do not initialize
it. To declare a pointer, we use the ( * ) dereference operator before its
name.
int *ptr;
• The pointer declared here will point to some random memory address
as it is not initialized. Such pointers are called wild pointers.
Types of Pointers in C
1. Integer Pointers
2. Array Pointers
3. Structure Pointer
4. Function Pointers
5. Double Pointers
6. NULL Pointer
7. Void Pointer
8. Wild Pointers
9. Constant Pointers
1. Integer Pointers
• As the name suggests, these are the pointers that point to the integer values.
• Syntax
int *ptr;
2. Array Pointer
• Pointers and Array are closely related to each other. Even the array name is
the pointer to its first element. They are also known as Pointer to Arrays.
We can create a pointer to an array using the given syntax.
char *ptr = &array_name;
3. Structure Pointer
• The pointer pointing to the structure type is called Structure Pointer or
Pointer to Structure. It can be declared in the same way as we declare the
other primitive data types.
struct struct_name *ptr;
4. Function Pointers
• Function pointers point to the functions. They are different from the rest of
the pointers in the sense that instead of pointing to the data, they point to the
code. Let’s consider a function prototype – int func (int, char), the function
pointer for this function will be
• Syntax
int (*ptr)(int, char);
5. Double Pointers
• In C language, we can define a pointer that stores the memory address of
another pointer.
• Such pointers are called double-pointers or pointers-to-pointer.
• Instead of pointing to a data value, they point to another pointer.
• Syntax
datatype **pointer_name;
6. NULL Pointer
• The Null Pointers are those pointers that do not point to any memory location.
They can be created by assigning a NULL value to the pointer. A pointer of any
type can be assigned the NULL value.
• Syntax
data_type *pointer_name = NULL;
or
pointer_name = NULL;
It is said to be good practice to assign NULL to the pointers currently not in use.
7. Void Pointer
• The Void pointers in C are the pointers of type void.
• It means that they do not have any associated data type.
• They are also called generic pointers as they can point to any type and can
be typecasted to any type.
• Syntax
void * pointer_name;
8. Wild Pointers
• The Wild Pointers are pointers that have not been initialized with
something yet.
• These types of C-pointers can cause problems in our programs and can
eventually cause them to crash.
• If values is updated using wild pointers, they could cause data abort or data
corruption.
• Example
int *ptr;
char *str;
9. Constant Pointers
• In constant pointers, the memory address stored inside the pointer is
constant and cannot be modified once it is defined.
• It will always point to the same memory address.
• Syntax
data_type * const pointer_name;
Passing arguments to functions using pointers
• Passing the pointers to the function means the memory location of the
variables is passed to the parameters in the function, and then the operations
are performed.
• The function definition accepts these addresses using pointers, addresses are
stored using pointers.
Arguments Passing without pointer
• When we pass arguments without pointers the changes made by the function
would be done to the local variables of the function.
C program to pass arguments to function without a pointer:
#include <stdio.h>
void swap(int a, int b) {
int temp = a;
Output:
a = b;
Values after swap function are: 20, 10
b = temp; }
int main()
{
int a = 10, b = 20;
swap(a, b);
printf("Values after swap function are: %d, %d", a, b);
return 0;
}
Arguments Passing with pointers
• A pointer to a function is passed in this example.
• As an argument, a pointer is passed instead of a variable and its address is
passed instead of its value.
• As a result, any change made by the function using the pointer is
permanently stored at the address of the passed variable.
• In C, this is referred to as call by reference.
C program to pass arguments to function with pointers:
#include <stdio.h>
void swap(int * a, int * b) {
int temp;
temp = *a;
*a = *b; Output:
*b = temp; Values before swap function are: 10, 20
} Values after swap function are: 20, 10
int main() {
int a = 10, b = 20;
printf("Values before swap function are: %d, %d\n", a, b);
swap(&a, &b);
printf("Values after swap function are: %d, %d", a, b);
return 0;
}
Thank you