MODULE 4
Strings and pointers
Introduction to pointers:
int x=10;
◦ This statement executes, the compiler sets aside 4 bytes of memory to hold value 10.
◦ It also sets up a symbol table in which it adds the symbol x and the relative address in memory where those bytes
are set. ( created by compiler).
◦ So every variable has a value and a memory location associated with it.
◦ rvalue - Appears on the right side of the assignment statement (10).
◦ lvalue is the address.
◦ Pointers are nothing but the memory addresses
◦ a pointer is a variable that contains the memory
location of another variable.
Declaring pointers:
◦ A pointer provides access to a variable by using the address of the variable.
data_type *ptr_name;
◦ Here data type is the data type of the value that the pointer will point to.
Declaring integer pointer :
int x=10;
int *ptr;
ptr= &x;
1. ptr is the name of the pointer.
2. (*)informs the compiler that ptr is a pointer variable and int specifies that it will store address of integer
variable.
3. The last statement, ptr is assigned the address of x. the & operator retrieves the cell value (address) of x and
assigns it to the pointer ptr.
Pointer expression and pointer arithmetic:
◦ Like other variables pointer variables can also be used in expressions.
Important points w.r.t Pointers
◦ A pointer variable can be assigned the address of another variable of the same type
◦ a pointer variable can be initialised with a null value.
◦ Prefix or postfix increment and decrement operators can be applied on a pointer variable.
◦ Pointer variable can be compared with another pointer variable of the same type using relational operators.
Some of the valid statements:
1)(*ptr)++
2) *pch+32; *pt%2;
3) if(*ptr<0)
4)while(*pnum <=*pn)
Passing arguments to functions using pointers: ( similar to call by reference)
◦ When ever we want to modify the value or code of the functions without making a copy of it, we must pass the
address of the variables to the functions.
◦ The calling function sends the address of the variables and the called function declare those incoming
arguments as pointers.
◦ How to use pointers for passing arguments to a function the programmer must do the following:
1. Declare the function parameters as pointers.
2. Use the deferenced pointers in the function body.
3. Pass the address as the actual argument, when the function is called.
Assignment:
1. Write a program to add 2 floating point numbers. The result should contain only 2 digits after the
decimal.
2. Write a program to calculate circle of area using pointers.
3. Write a program to test whether a number is positive negative or equal to zero.
4. Write a program to swap 2 integer numbers using function with pointer.
5. Write a program to print all even numbers from m to n.
Strings:
◦ String is a null terminated character array.
◦ This means after the last character a null character( \0) is stored to the end of the character array.
◦ char str[]= “HELLO”; to store 5 character array we need 5+1 locations.
◦ Subscript are used to access the elements of the character array.
◦ The subscript start with zero. The character strings are stored in successive memory locations.
char str[]= {‘H’,’E’,’L’,’L’,’O’}; // valid statement
char str[10]=“HELLO” ; //valid statement
char str[5];
str= “HELLO” ; 🡪 invalid statement. Declaration and initialization cannot be separated.
scanf(“%s”,&str); // using & with string variable might generate error.
Reading the strings:
char str[100];
Then str can be read in three ways:
1. Using scanf function
2. Using gets function
3. Using getchar(), getch() or getche() (MS-DOS compiler like Turbo C or Borland C)
Limitation of scanf()
◦ The function terminates as soon as it finds a blank space and append a null character.
◦ If the user enters hello world, then str will contain only hello.
◦ White space character is left in the input stream.
◦ This is because the moment a blank space is encountered the string is terminated by the scanf function.
To overcome the limitation of scanf, gets is used.
char str[25];
gets(str);
The input taken with gets is automatically terminated with the null character.
Limitation of scanf() or strings:
Illustration of gets()
Strings can be read by calling getchar() function by calling repeatedly
Writing strings:
1. printf()
2. puts()
3. putchar()
in printf we have to exclusively give \n to terminate with new line character.
puts(str);
◦ It terminates the line with a new line character.
◦ It returns EOF (-1) if an error occurs and returns positive number on success.
putchar()
Suppressing the input:
◦ The scanf() function can be used to read a field without assigning any variable to it.
◦ This is done by preceding the fields's format code with a *. (* is assignment suppression character.)
◦ scanf(“%d%*c%d”, &hr, &min);
◦ The time can be read as 9:05 or 9.05
◦ Here the colon would be read but not assigned to anything.
◦ Assignment supressing is particularly useful when part of what is input needs to be ignored/supressed .
Using a scanset:
scanset can be used to define a set of characters which may be read and assigned to the
corresponding string
scanf(“%10[aeiou]”, str);
sprintf() function
int sprintf(char *buffer, const char *format [,arguments,…]);
◦ The output is written to memory area rather than directly to standard output
◦ buf is the place string should be stored
◦ Format is the string that contains the text to be printed.
◦ Example:
char buf[100];
int num=10;
sprintf(buf, “num=%d”, num);
sscanf()
◦ Accepts the string from which to read the input
sscanf(str, “%d”, &num);
String taxonomy:
char name[10] = "John";
char word[] = "Hello";
Operations on String:
1. Finding the length of a string
2. Converting characters of a string into uppercase
3. converting characters of string into lower case
4. concatenating 2 strings to form a new string
5. appending string to another string
6. comparing 2 strings
7. String copy
8. reversing a string
9. extracting a substring from left
10. extracting a substring from right
11. extracting a substring from the middle of a string
12. inserting a string in another string
13. replacing a pattern with another pattern in a string
String manipulation function:
These following functions are present in string.h.
strcat:
char *strcat (char *str1, const char *str2)
◦ Appends the string pointed to by str2 to the end of
string pointed to str1.
strncat:char *strcat (char *str1, const char *str2, size_t n);
Syntax:
◦ This function appends the string pointed to by str2 to the end of the string pointed to str1 up to n characters
long.
◦ Copying stops when n characters are copied.
◦ A terminating null character is appended to str1 before returning to the calling function.
strcmp:
int strcmp ( const char *str1, const char *str1);
◦ Compares the string pointed to by str1 to the string pointed to by str2.
◦ strcmp function in C does not compare just the first character of the strings. It compares the strings character by character
until it finds a difference or reaches the end of the strings
◦ The function returns zero if the strings are equal.
◦ otherwise it returns a Value less than zero if str1 is less than str2 or greater than 0 otherwise.
strncmp:
int strcmp ( const char *str1, const char *str1, size_t n);
◦ Compares at most first n bytes of str1 and str2.
strcpy:
char *strcpy(char *str1, const char *str2);
strncpy:
char *strcpy(char *str1, const char *str2, size_t n);
strlen
size_t strlen (const char *str);
strstr:
char *strstr(char *str1, const char *str2);
◦ To find the first occurrence of string str2 in the string str1
◦ Will return 1 if substring is present.
C doesn’t have a built-in function to reverse a given string.
Code to find length of string without using
inn built function
Assignment programs:
1. C program to find the reverse of a string
2. C program to find the length tof given string
3. Program to find the given string is palindrome or not
Arrays of string:
◦ String is an array of characters.
◦ Array of strings is collections of strings [2D]
char name[5][10] ={“ram”,”mohan”,”shyam”,”hari”,”gopal”};
Please refer the text book for more programs and try to understand.