Arrays
C Array
An array is defined as the collection of similar type of data items stored at contiguous memory locations.
Arrays are the derived data type in C programming language which can store the primitive type of data
such as int, char, double, float, etc. It also has the capability to store the collection of derived data types,
such as pointers, structure, etc. The array is the simplest data structure where each data element can be
randomly accessed by using its index number.
C array is beneficial if you have to store similar elements. For example, if we want to store the marks of
a student in 6 subjects, then we don't need to define different variables for the marks in the different
subject. Instead of that, we can define an array which can store the marks in each subject at the
contiguous memory locations.
By using the array, we can access the elements easily. Only a few lines of code are required to access
the elements of the array.
Properties of Array
The array contains the following properties.
o Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
o Elements of the array are stored at contiguous memory locations where the first element is stored
at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address of each
element of the array with the given base address and the size of the data element.
Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the limit.
So, it doesn't grow the size dynamically like LinkedList which we will learn later.
Declaration of C Array
To create an array, define the data type (like int) and specify the name of the array
followed by square brackets [].
We can declare an array in the c language in the following way.
1. data_type array_name[array_size];
Now, let us see the example to declare the array.
1. int marks[5];
Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can initialize each
element of the array by using the index. Consider the following example.
1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;
Access the Elements of an Array
To access an array element, refer to its index number.
Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
This statement accesses the value of the first element [0] in myNumbers:
int myNumbers[] = {25, 50, 75, 100};
printf("%d", myNumbers[0]);
// Outputs 25
Change an Array Element
To change the value of a specific element, refer to the index number:
int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;
printf("%d", myNumbers[0]);
// Now outputs 33 instead of 25
C array example
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5];//declaration of array
5. marks[0]=80;//initialization of array
6. marks[1]=60;
7. marks[2]=70;
8. marks[3]=85;
9. marks[4]=75;
10. //traversal of array
11. for(i=0;i<5;i++){
12. printf("%d \n",marks[i]);
13. }//end of for loop
14. return 0;
15. }
Output
80
60
70
85
75
C Array: Declaration with Initialization
We can initialize the c array at the time of declaration. Let's see the code.
1. int marks[5]={20,30,40,50,60};
In such case, there is no requirement to define the size. So it may also be written as the following
code.
1. int marks[]={20,30,40,50,60};
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5]={20,30,40,50,60};//declaration and initialization of array
5. //traversal of array
6. for(i=0;i<5;i++){
7. printf("%d \n",marks[i]);
8. }
9. return 0;
10. }
Output
20
30
40
50
60
Entering Data into an Array
Here is the section of code that places data into an array:
int marks[ 5 ] ;
for ( i = 0 ; i <= 4 ; i++ )
{
printf ( "Enter marks " ) ;
scanf ( "%d", &marks[ i ] ) ;
we have used the “address of” operator (&) on the element marks[ i ] of the array.
Notes:-
Till the array elements are not given any specific values, they are supposed to contain garbage
values
What happens in memory when we make this declaration? 32 bytes get immediately reserved in memory, 4 bytes
each for the 8 integers. And since the array is not being initialized, all eight values present in it would be garbage
values
Two Dimensional Array in C
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices
which can be represented as the collection of rows and columns. However, 2D arrays are created to
implement a relational database lookalike data structure. It provides ease of holding the bulk of data at
once which can be passed to any number of functions wherever required.
Declaration of two dimensional Array in C
The syntax to declare the 2D array is given below.
1. data_type array_name[rows][columns];
Consider the following example.
1. int twodimen[4][3];
Here, 4 is the number of rows, and 3 is the number of columns.
Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the declaration and initialization are
being done simultaneously. However, this will not work with 2D arrays. We will have to define at least
the second dimension of the array. The two-dimensional array can be declared and defined in the
following way.
1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Two-dimensional array example in C
1. #include<stdio.h>
2. int main(){
3. int i=0,j=0;
4. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
5. //traversing 2D array
6. for(i=0;i<4;i++){
7. for(j=0;j<3;j++){
8. printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
9. }//end of j
10. }//end of i
11. return 0;
12. }
Output
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
Let us try to write a program to find average marks obtained by a class of 30 students in a test.
# include <stdio.h>
int main( )
{
int avg, sum = 0 ;
int i ;
int marks[ 30 ] ; /* array declaration */
for ( i = 0 ; i <= 29 ; i++ )
{
printf ( "Enter marks " ) ;
scanf ( "%d", &marks[ i ] ) ; /* store data in array */
}
for ( i = 0 ; i <= 29 ; i++ )
sum = sum + marks[ i ] ; /* read data from an array*/
avg = sum / 30 ;
printf ( "Average marks = %d\n", avg ) ;
return 0 ;
}
Strings
Strings are used for storing text/characters.
For example, "Hello World" is a string of characters.
Unlike many other programming languages, C does not have a String type to easily create
string variables. Instead, you must use the char type and create an array of characters to
make a string in C:
String in C programming is a sequence of characters terminated with a null character ‘\0’.
Strings are defined as an array of characters. The difference between a character array and
a string is the string is terminated with a unique character ‘\0’.
Example of C String:
Declaration of Strings
Declaring a string is as simple as declaring a one-dimensional array. Below is the basic
syntax for declaring a string.
char str_name[size];
In the above syntax str_name is any name given to the string variable and size is used to
define the length of the string, i.e the number of characters strings will store.
Note: There is an extra terminating character which is the Null character (‘\0’) used to
indicate the termination of a string that differs strings from normal character arrays.
When a Sequence of characters enclosed in the double quotation marks is encountered by
the compiler, a null character ‘\0’ is appended at the end of the string by default.
Initializing a String
A string can be initialized in different ways. We will explain this with the help of an example.
Below are the examples to declare a string with the name str and initialize it with
“HelloWorld”.
4 Ways to Initialize a String in C
1. Assigning a string literal without size: String literals can be assigned without size.
Here, the name of the string str acts as a pointer because it is an array.
char str[] = " HelloWorld ";
(string by the string literal )
2. Assigning a string literal with a predefined size: String literals can be assigned with a
predefined size. But we should always account for one extra space which will be assigned
to the null character. If we want to store a string of size n then we should always declare a
string with a size equal to or greater than n+1.
char str[50] = " HelloWorld";
3. Assigning character by character with size: We can also assign a string character by
character. But we should remember to set the end character as ‘\0’ which is a null character.
char str[11] = { 'H','e','l','l','o','W','o','r','l',’d’,'\0'};
(String by char array )
4. Assigning character by character without size: We can assign character by character
without size with the NULL character at the end. The size of the string is determined by the
compiler automatically.
char str[] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
Difference between char array and string literal
There are two main differences between char array and literal.
o We need to add the null character '\0' at the end of the array by ourself whereas, it is appended internally
by the compiler in the case of the character array.
o The string literal cannot be reassigned to another set of characters whereas, we can reassign the
characters of the array.
String Example in C
Let's see a simple example where a string is declared and being printed. The '%s' is used as a format
specifier for the string in c language.
#include<stdio.h>
#include <string.h>
int main(){
char ch[11]={'s', 's', '', 'a', 's', 'i', 't', 'm', 's', 'c', '\0'};
char ch2[11]="ssasitmsc";
printf("Char Array Value is: %s\n", ch);
printf("String Literal Value is: %s\n", ch2);
return 0;
}
Output
Char Array Value is: ssasitmsc
String Literal Value is: ssasitmsc
How to Read a String From User?
// C program to read string from user
#include<stdio.h>
int main()
{
// declaring string
char str[50];
// reading string
scanf("%s",str);
// print string
printf("%s",str);
return 0;
}
Standard Library String Functions
Function Use
strlen Finds length of a string
strlwr Converts a string to lowercase
strupr Converts a string to uppercase
strcat Appends one string at the end of another
strncat Appends first n characters of a string at the end of another
strcpy Copies a string into another
strncpy Copies first n characters of one string into another
strcmp Compares two strings
Strncmp Compares first n characters of two strings
strcmpi Compares two strings without regard to case ("i" denotes that this function ignores
case)
stricmp Compares two strings without regard to case (identical to strcmpi)
strnicmp Compares first n characters of two strings without regard to case
strdup Duplicates a string
strchr Finds first occurrence of a given character in a string
strrchr Finds last occurrence of a given character in a string
strstr Finds first occurrence of a given string in another string
strset Sets all characters of string to a given character
strnset Sets first n characters of a string to a given character
strrev Reverses string
strlen( )
This function counts the number of characters present in a string. Its usage is illustrated in the following program.
#include <stdio.h>
#include <string.h>
int main( )
{
char arr[ ] = "Bamboozled" ;
int len1, len2 ;
len1 = strlen ( arr ) ;
len2 = strlen ( "Humpty Dumpty" ) ;
printf ( "\nstring = %s length = %d", arr, len1 ) ;
printf ( "\nstring = %s length = %d", "Humpty Dumpty", len2 ) ;
return 0;
The output would be...
string = Bamboozled length = 10
string = Humpty Dumpty length = 13
Note that in the first call to the function strlen( ), we are passing the base address of the string, and the function in turn
returns the length of the string. While calculating the length it doesn’t count ‘\0’. Even in the second call,
len2 = strlen ( "Humpty Dumpty" ) ;
what gets passed to strlen( ) is the address of the string and not the string itself.
strcpy( )
This function copies the contents of one string into another. The base addresses of the source and target strings should be
supplied to this function. Here is an example of strcpy( ) in action...
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = "Sayonara" ;
char target[20] ;
strcpy ( target, source ) ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
return 0;
}
And here is the output...
source string = Sayonara
target string = Sayonara
strncpy()
The strncpy() function is similar to strcpy() function, except that at most n bytes of src are copied
char *strncpy( char *dest, const char *src, size_t n )
Parameters: This function accepts three parameters as mentioned above and described below:
src: The string which will be copied.
dest: Pointer to the destination array where the content is to be copied.
n: The first n character copied from src to dest.
/ C Program to illustrate the
// strcpy() function in C/C++
#include <stdio.h>
#include <string.h>
int main()
{
char src[] = "geeksforgeeks";
// The destination string size is 5.
char dest[5];
// copying n bytes of src into dest.
strncpy(dest, src, 5);
printf("Copied string: %s\n", dest);
return 0;
}
Output:
Copied string: geeks
strncat()
This function appends not more than n characters from the string pointed to by src to the end of the string pointed to by dest
plus a terminating Null-character.
// C, program demonstrate functionality of strncat()
#include <stdio.h>
#include <string.h>
int main()
{
// Take any two strings
char src[50] = "efghijkl";
char dest[50]= "abcd";
// Appends 5 character from src to dest
strncat(dest, src, 5);
// Prints the string
printf("Source string : %s\n", src);
printf("Destination string : %s", dest);
return 0;
}
Output:
Source string : efghijkl
Destination string : abcdefghi
strcat( )
This function concatenates the source string at the end of the target string. For example, “Bombay” and “Nagpur” on
concatenation would result into a string “BombayNagpur”. Here is an example of strcat( ) at work.
main( )
{
char source[ ] = "Surat" ;
char target[30] = "Hello" ;
strcat ( target, source ) ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
}
And here is the output...
source string = Surat
target string = HelloSurat
strcmp( )
This is a function which compares two strings to find out whether they are same or different. The two strings are compared
character by character until there is a mismatch or end of one of the strings is reached, whichever occurs first. If the two
strings are identical, strcmp( ) returns a value zero. If they’re not, it returns the numeric difference between the ASCII
values of the first non-matching pairs of characters. Here is a program which puts strcmp( ) in action.
main( )
{
char string1[ ] = "Jerry" ;
char string2[ ] = "Ferry" ;
int i, j, k ;
i = strcmp ( string1, "Jerry" ) ;
j = strcmp ( string1, string2 ) ;
k = strcmp ( string1, "Jerry boy" ) ;
printf ( "\n%d %d %d", i, j, k ) ;
}
And here is the output...
0 4 -32
4, which is the numeric difference between ASCII value of ‘J’ and ASCII value of ‘F’.
In the third call to strcmp( ) “Jerry” doesn’t match with “Jerry boy”, because the null character at the end of “Jerry”
doesn’t match the blank in “Jerry boy”. The value returned is -32, which is the value of null character minus the ASCII
value of space, i.e., ‘\0’ minus ‘ ’, which is equal to -32.
strcmpi()
The strcmpi() function is a built-in function in C and is defined in the “string.h” header file. The strcmpi()
function is same as that of the strcmp() function but the only difference is that strcmpi() function is not
case sensitive and on the other hand strcmp() function is the case sensitive.
int strcmpi (const char * str1, const char * str2 );
int main( )
{
char str1[] = "geeks" ;
char str2[] = "geeks" ;
int j = strcmpi ( str1, str2 ) ;
printf ( "The function returns = %d",j ) ;
return 0;
}
And here is the output...
0
stricmp()
stricmp() is one of the inbuilt string function in c programming which is used to compare two
strings without any discrimination between uppercase and lowercase letters, if the strings are
same, it returns 0. Otherwise it returns a nonzero value
#include <stdio.h>
#include<string.h>
int main()
{
char str1[20] = "this is stricmp";
char str2[20] = "THIS IS STRICMP";
int n;
n = stricmp(str1, str2);
if( n == 0)
printf("The strings str1 and str2 are same ");
else if(n == -1)
printf("The string str1 is lesser than str2");
else
printf("The string str1 is greater than str2");
return 0;
}
The strings str1 and str2 are same
strnicmp()
Compare Substrings Without Case Sensitivity
#include <stdio.h>
#include <string.h>
int main(void)
{
char *str1 = "THIS IS THE FIRST STRING";
char *str2 = "This is the second string";
int numresult;
/* Compare the first 11 characters of str1 and str2
without regard to case */
numresult = strnicmp(str1, str2, 11);
if (numresult < 0)
printf("String 1 is less than string2.\n");
else
if (numresult > 0)
printf("String 1 is greater than string2.\n");
else
printf("The two strings are equivalent.\n");
return 0;
}
Output.
The two strings are equivalent.
strdup()
The strdup() and strndup() functions are used to duplicate a string.
Syntax : char *strdup(const char *s);
This function returns a pointer to a null-terminated byte string, which is a duplicate of the string pointed to
by s. The memory obtained is done dynamically using malloc and hence it can be freed using free().
It returns a pointer to the duplicated string s.
Below is the C implementation to show the use of strdup() function in C:
// C program to demonstrate strdup()
#include<stdio.h>
#include<string.h>
int main()
{
char source[] = "GujaratSuratCity";
// A copy of source is created dynamically
// and pointer to copy is returned.
char* target = strdup(source);
printf("%s", target);
return 0;
}
Output:
GujaratSuratCity
Strchr();
The C library function char *strchr(const char *str, int c) searches for the first occurrence of the character c (an
unsigned char) in the string pointed to by the argument str.
Declaration
Following is the declaration for strchr() function.
char *strchr(const char *str, int c)
Parameters
str − This is the C string to be scanned.
c − This is the character to be searched in str.
Return Value
This returns a pointer to the first occurrence of the character c in the string str, or NULL if the character
is not found.
#include <stdio.h>
#include <string.h>
int main () {
const char str[] = "[Link] ";
const char ch = '.';
char *ret;
ret = strchr(str, ch);
printf("String after |%c| is - |%s|\n", ch, ret);
return(0);
}
Let us compile and run the above program that will produce the following result −
String after |.| is - |. [Link] |
Strrchr()
Description
The C library function char *strrchr(const char *str, int c) searches for the last occurrence of the character c (an
unsigned char) in the string pointed to, by the argument str.
Declaration
Following is the declaration for strrchr() function.
char *strrchr(const char *str, int c)
Parameters
str − This is the C string.
c − This is the character to be located. It is passed as its int promotion, but it is internally converted
back to char.
Return Value
This function returns a pointer to the last occurrence of character in str. If the value is not found, the function
returns a null pointer.
#include <stdio.h>
#include <string.h>
int main () {
int len;
const char str[] = "[Link]";
const char ch = '.';
char *ret;
ret = strrchr(str, ch);
printf("String after |%c| is - |%s|\n", ch, ret);
return(0);
}
Let us compile and run the above program that will produce the following result −
String after |.| is - |.com|
Strstr()
This function takes two strings s1 and s2 as an argument and finds the first occurrence of the sub-
string s2 in the string s1. The process of matching does not include the terminating null-characters(‘\0’),
but function stops there
Syntax:
char *strstr (const char *s1, const char *s2);
Parameters:
s1: This is the main string to be examined.
s2: This is the sub-string to be searched in s1 string.
Return Value: This function returns a pointer points to the first character of the found s2 in s1 otherwise a
null pointer if s2 is not present in s1. If s2 points to an empty string, s1 is returned.
// CPP program to illustrate strstr()
#include <string.h>
#include <stdio.h>
int main()
{
// Take any two strings
char s1[] = "GeeksforGeeks";
char s2[] = "for";
char* p;
// Find first occurrence of s2 in s1
p = strstr(s1, s2);
// Prints the result
if (p) {
printf("String found\n");
printf("First occurrence of string '%s' in '%s' is '%s'", s2, s1, p);
} else
printf("String not found\n");
return 0;
}
Output:
String found
First occurrence of string 'for' in 'GeeksforGeeks' is 'forGeeks'
strlwr()
The strlwr(string) function returns string characters in lowercase. Let's see a simple example of strlwr() function.
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nLower String is: %s",strlwr(str));
return 0;
}
Output
Enter string: SSASITmsc
String is: SSASITmsc
Lower String is: ssasitmsc
strupr()
The strupr(string) function returns string characters in uppercase. Let's see a simple example of strupr()
function.
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nUpper String is: %s",strupr(str));
return 0;
}
Output:
Enter string: ssasit
String is: ssasit
Upper String is: SSASIT
strnset()
The strnset() function is a builtin function in C and it sets the first n characters of a string to a given
character. If n is greater than the length of string, the length of string is used in place of n.
Syntax:
char *strnset(const char *str, char ch, int n);
Return Value: It returns the modified string obtained after replacing the first characters of the given
string str
// C program to illustrate
// the strnset() function
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "Computer Science";
printf("Original String: %s\n", str);
// First 5 character of string str
// replaced by character '*'
printf("Modified String: %s\n", strnset(str, '*', 5));
return 0;
}
Original String: Computer Science
Modified String: *****ter Science
Strrev()
The strrev() function is a built-in function in C and is defined in string.h header file. The strrev() function is
used to reverse the given string.
Syntax:
char *strrev(char *str);
Parameter:
str: The given string which is needed to be reversed.
Returns: This function doesn’t return anything but the reversed string is stored in the same string.
// C program to demonstrate
// example of strrev() function
#include <stdio.h>
#include <string.h>
int main()
{
char str[50] = "123456789";
printf("The given string is =%s\n", str);
printf("After reversing string is =%s", strrev(str));
return 0;
}
Output:
The given string is = 123456789
After reversing string is = 987654321
Storing Strings as Character Arrays
The strings declared as character arrays are stored like other arrays in C. For example, if str[] is an auto
variable, the string is stored in the stack segment; if it’s a global or static variable, then stored in the data
segment.
Strings as character arrays can be stored in two ways:
char str[6] = "Ninja"; /*One extra for string terminator*/
char str[6] = {‘N‘,‘i’, ‘n’, ‘j‘, ‘a‘, '\0'}; /* '\0' is string terminator */
Storing Strings as Character Pointers
Strings can be stored using character pointers in two ways:
Read-only string in a shared segment.
The directly assigned string values to a pointer are stored in a read-only block shared among functions in most
compilers.
char *str = "Ninja";
The word “Ninja” is stored in a shared read-only location while the pointer str is stored in read-write memory.
The pointer str can be changed to point to something else, but it cannot change the value at the present str. So
this kind of string should be used only when the string is not modified at a later stage in the program.
Dynamically allocated in the heap segment.
Strings are stored like other dynamically allocated things in C and shared among functions.
char *str;
int size = 6; /*one extra for ‘\0’*/
str = (char *)malloc(sizeof(char)*size);
*(str+0) = 'N';
*(str+1) = 'i';
*(str+2) = 'n';
*(str+3) = 'j';
*(str+4) = 'a';
*(str+5) = '\0';
Example 1 (Try to modify string)
The below program may crash (gives segmentation fault error) because the line *(str+1) =
‘n’ tries to write a read only memory.
int main()
{
char *str;
str = "GfG"; /* Stored in read only part of data segment */
*(str+1) = 'n'; /* Problem: trying to modify read only memory */
getchar();
return 0;
}
The below program works perfectly fine as str[] is stored in writable stack segment.
int main()
{
char str[] = "GfG"; /* Stored in stack segment like other auto variables */
*(str+1) = 'n'; /* No problem: String is now GnG */
getchar();
return 0;
}