Difference Between Array and String in C

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

Difference Between Array and String

in C
Arrays and strings are two extensively used data types in the C programming
language, although they have significant differences in their features, usefulness, and
applications. In this post, we will look at how arrays and strings differ in the C
programming language.

Definition and Properties


An array is a collection of pieces of the same data type that are stored in memory in
contiguous locations. An array's elements can be retrieved using an index spanning
from 0 to the array's size minus one. Characters, integers, floating-point numbers,
and structures can all be stored in arrays. When we declare an array in C, we must
define its data type, size, and, if desired, the starting values of its entries.

A string is a series of characters that ends with a null character ('0'). Strings are
represented in C as arrays of characters, with the final character being a null
character. Strings can be defined and handled using the C library's string handling
functions, such as strlen(), strcat(), strcpy(), and strcmp(). A string literal in C is
surrounded in double quotes (" ") and is terminated by a null character by default.

Strings have the critical virtue of being immutable, which implies that we cannot
change the individual characters of a string once it is produced. We can, however,
make a new string by concatenating or copying existing ones. Arrays, on the other
hand, are changeable, which means we can change the elements of an array using
assignment statements or pointer arithmetic.

Backward Skip 10sPlay VideoForward Skip 10s

Size and Memory Allocation


One significant distinction between arrays and strings is that the size of an array is
fixed at the moment of declaration and cannot be changed during programme
execution, whereas the size of a string can fluctuate based on the number of
characters it contains. An array of five integers, for example, has a fixed size of 20
bytes (assuming each integer is four bytes), whereas a string of five characters has a
fixed size of six bytes (five characters plus the null character).

When declaring an array in C, we must indicate its size explicitly by providing a


constant value or using an initialized variable. For example, we may define an integer
array this way:
1. int arr[5]; // declares an array of 5 integers

In C, on the other hand, we may skip the size and let the compiler allocate the
appropriate memory automatically. For instance, we could declare a string as follows:

1. char str[] = "hello"; // declares a string of 6 characters

The compiler allocates six bytes of memory in this example for keeping the string
"hello" (five characters plus the null character).

Accessing and Manipulating Elements


Individual elements in an array can be accessed and manipulated using their indexes.
An array's first element has an index of 0, and its last element has an index of size
minus one. A for loop can iterate over an array's elements and execute operations on
them, such as sorting, searching, and printing. Here's an instance of accessing and
updating an array element:

1. int arr[5] = {1, 2, 3, 4, 5};


2. arr[2] = 10; // changes the third element to 10

In this example, the third element of the array (with index 2) is changed to 10.

Individual characters in a string can be accessed using their indices, much like in an
array. However, because strings are immutable, we cannot directly change their
characters. We can instead make a new string by concatenating or copying existing
ones. String manipulation routines provided by the C library include strlen(), strcat(),
strcpy(), and strcmp().

Here is an example of manipulating a string using the strcpy() function:

1. char str1[] = "hello";


2. char str2[] = "world";
3. strcpy(str1, str2); // copies the contents of str2 to str1

In this example, the contents of str2 are copied to str1, overwriting the original
contents of str1.

Null Termination
The null termination of strings is a significant difference between arrays and strings
in C. A string must always finish with a null character ('0'), which signifies that the
string has come to a conclusion. String handling methods would be unable to
determine where the string terminates in the absence of a null character, resulting in
undefined behaviour or even programme failures.

Arrays, on the other hand, do not require null termination since they can store any
type of data, including binary data and non-printable characters. However, in arrays,
null termination is occasionally used to indicate the conclusion of a sequence of
elements, such as a list of letters or a data stack.

Applications
Depending on their qualities and functions, arrays and strings are employed in
various applications in the C programming language. Arrays are helpful for storing a
set number of pieces of the same data type, such as a grade list, a number matrix, or
a set of flags. Arrays can also be used to build data structures like stacks, queues, and
heaps.

Strings, on the other hand, are used to store text and character data like names,
addresses, and messages. Strings are commonly used in input/output tasks like
reading and writing to files or the terminal. Strings are extensively utilized in network
programming and database management, where text is frequently sent or saved.

Here is an example C code that demonstrates the


difference between arrays and strings:
C Program:

1. #include <stdio.h>
2. #include <string.h>
3.
4. int main() {
5. int arr[5] = {1, 2, 3, 4, 5}; // declaring an array of integers
6. char str[] = "hello"; // declaring a string of characters
7.
8. // accessing elements of the array
9. printf("The third element of the array is %d\n", arr[2]); // output: The third element
of the array is 3
10.
11. // accessing elements of the string
12. printf("The third character of the string is %c\n", str[2]); // output: The third charact
er of the string is l
13.
14. // modifying elements of the array
15. arr[2] = 10; // changing the value of the third element of the array
16. printf("The new value of the third element of the array is %d\n", arr[2]); // output: T
he new value of the third element of the array is 10
17.
18. // modifying elements of the string
19. str[2] = 'L'; // changing the value of the third character of the string
20. printf("The new value of the third character of the string is %c\n", str[2]); // output:
The new value of the third character of the string is L
21.
22. // copying arrays
23. int arr_copy[5];
24. memcpy(arr_copy, arr, sizeof(arr)); // copying the contents of arr to arr_copy
25. printf("The first element of the copied array is %d\n", arr_copy[0]); // output: The fi
rst element of the copied array is 1
26.
27. // copying strings
28. char str_copy[10];
29. strcpy(str_copy, str); // copying the contents of str to str_copy
30. printf("The copied string is %s\n", str_copy); // output: The copied string is hello
31.
32. return 0;
33. }

Output:

The third element of the array is 3


The third character of the string is l
The new value of the third element of the array is 10
The new value of the third character of the string is L
The first element of the copied array is 1
The copied string is heLlo

Explanation:

o This code demonstrates the difference between arrays and strings in C. In the
beginning, we declare an array arr of 5 integers with values 1, 2, 3, 4, and 5,
and a string str with the value "hello". We then access and print the third
element of the array using arr[2], which has the value 3, and the third
character of the string using str[2], which has the value 'l'.
o Next, we modify the third element of the array using arr[2] = 10, which
changes its value from 3 to 10. We also modify the third character of the
string using str[2] = 'L', which changes its value from 'l' to 'L'.
o We then demonstrate how to copy arrays and strings using the memcpy() and
strcpy() functions, respectively. We declare a new array arr_copy and use the
memcpy() function to copy the contents of arr to arr_copy. We also declare a
new string str_copy and use the strcpy() function to copy the contents of str to
str_copy. We print the first element of arr_copy, which has the value 1, and the
contents of str_copy, which is "helloL". Note that the modified character 'L' is
also copied to str_copy.
o Finally, we return 0 to indicate a successful termination of the program.

Conclusion
In conclusion, arrays and strings are two essential data types in C programming
language, with distinct properties, functionalities, and applications. Arrays are
collections of elements of the same data type, with a fixed size and mutable contents.
Strings are sequences of characters terminated by a null character, with a variable
size and immutable contents. Understanding the differences between arrays and
strings is crucial for writing efficient and robust C programs.
A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

Functions are used to perform certain actions, and they are important for
reusing code: Define the code once, and use it many times.

Predefined Functions
So it turns out you already know what a function is. You have been using it
the whole time while studying this tutorial!

For example, main() is a function, which is used to execute code,


and printf() is a function; used to output/print text to the screen:

Example
int main() {
printf("Hello World!");
return 0;
}

Try it Yourself »

Create a Function
To create (often referred to as declare) your own function, specify the name
of the function, followed by parentheses () and curly brackets {}:

Syntax
void myFunction() {
// code to be executed
}
Example Explained

 myFunction() is the name of the function


 void means that the function does not have a return value. You will
learn more about return values later in the next chapter
 Inside the function (the body), add code that defines what the function
should do

Call a Function
Declared functions are not executed immediately. They are "saved for later
use", and will be executed when they are called.

To call a function, write the function's name followed by two


parentheses () and a semicolon ;

In the following example, myFunction() is used to print a text (the action),


when it is called:

Example
Inside main, call myFunction():

// Create a function
void myFunction() {
printf("I just got executed!");
}

int main() {
myFunction(); // call the function
return 0;
}

// Outputs "I just got executed!"

Try it Yourself »

A function can be called multiple times:

Example
void myFunction() {
printf("I just got executed!");
}

int main() {
myFunction();
myFunction();
myFunction();
return 0;
}

// I just got executed!


// I just got executed!
// I just got executed!

Try it Yourself »

C Exercises
Test Yourself With Exercises
Exercise:
Create a method named myFunction and call it inside main().

void {
printf("I just got executed!");
}

int main() {

return 0;
}
 Enables reusability and reduces redundancy

 Makes a code modular

 Provides abstraction functionality

 The program becomes easy to understand and manage

 Breaks an extensive program into smaller and simpler pieces

Basic Syntax of Functions

The basic syntax of functions in C programming is:

return_type function_name(arg1, arg2, … argn){

Body of the function //Statements to be processed

In the above syntax:


 return_type: Here, we declare the data type of the value returned by functions. However,
not all functions return a value. In such cases, the keyword void indicates to the compiler
that the function will not return any value.

 function_name: This is the function’s name that helps the compiler identify it whenever
we call it.

 arg1, arg2, ...argn: It is the argument or parameter list that contains all the parameters to be
passed into the function. The list defines the data type, sequence, and the number of
parameters to be passed to the function. A function may or may not require parameters.
Hence, the parameter list is optional.

 Body: The function’s body contains all the statements to be processed and executed
whenever the function is called.

Note: The function_name and parameters list are together known as the signature of a
function in C programming.

Aspects of Functions in C Programming

Functions in C programming have three general aspects: declaration, defining, and calling.
Let’s understand what these aspects mean.

1. Function Declaration

The function declaration lets the compiler know the name, number of parameters, data types
of parameters, and return type of a function. However, writing parameter names during
declaration is optional, as you can do that even while defining the function.

2. Function Call

As the name gives out, a function call is calling a function to be executed by the compiler.
You can call the function at any point in the entire program. The only thing to take care of is
that you need to pass as many arguments of the same data type as mentioned while declaring
the function. If the function parameter does not differ, the compiler will execute the program
and give the return value.

3. Function Definition

It is defining the actual statements that the compiler will execute upon calling the function.
You can think of it as the body of the function. Function definition must return only one
value at the end of the execution.
Here’s an example with all three general aspects of a function.

#include <stdio.h>

// Function declaration

int max_Num(int i, int j){

// Function definition

if (i > j)

return i;

else

return j;

// The main function. We will discuss about it later

int main(void){

int x = 15, y = 20;

// Calling the function to find the greater number among the two

int m = max_Num(x, y);

printf("The bigger number is %d", m);

return 0;

}
Types of Functions in C Programming

Functions in C programming are classified into two types:

1. Library Functions

Also referred to as predefined functions, library functions are already defined in the C
libraries. This means that we do not have to write a definition or the function’s body to call
them. We can simply call them without defining them as they are already defined. However,
we need to include the library at the beginning of the code for calling a library function. We
can then use the proper syntax of the function to call them. Printf(), scanf(), ceil(), and floor()
are examples of library functions.

2. User-Defined Functions

These are the functions that a developer or the user declares, defines, and calls in a program.
This increases the scope and functionality, and reusability of C programming as we can
define and use any function we want. A major plus point of C programming is that we can
add a user-defined to any library to use it in other programs.

Header Files for Library Functions in C Programming

As mentioned earlier, all library functions are included in different header files saved with
a .h extension. To use any library functions, you need to use the header files at the beginning
of the program. Without including the header files, the program will not be executed as the
compiler will throw errors. Here are the header files available in C.
Header File Description

The input/output header file


contains all the library functions
stdio.h
related to input and output
operations.

It is the console I/O file and


conio.h contains library functions for
console input/output operations.

This is the string header file that


string.h contains functions related to
working with strings.

The standard library consists of al


stdlib.h
general functions.

It is the math header file and


math.h contains all library functions relat
to math operations.

This header file consists of all the


time.h
time-related functions
The ctype.h file includes all
ctype.h
character handling functions.

This header file consists of all the


stdarg.h
variable argument functions.

The signal.h file contains all the


signal.h
signal handling functions.

All the jump functions are declare


setjmp.h
in this header file.

All the locale-related functions are


locale.h
defined in the locale header file.

The errno.h header file has all the


errno.h
error handling functions.

The assert.h file has all the


assert.h
functions used for diagnostic.

Different Ways of Calling a Function

Depending on whether the function accepts arguments or not and returns a value or not, there
can be four different aspects of C function calls, which are:
C Programming Functions Without Arguments and Return Value

A function in C programming may not accept an argument and return a value. Here’s an
example of such a function.

#include<stdio.h>

void main (){

printf("Welcome to ");

printName();

void printName(){

printf("Simplilearn");

Output:

C programming Functions With No Arguments But has a Return Value

A function can return a value without accepting any arguments. Here’s an example of
calculating and returning the area of a rectangle without taking any argument.

#include<stdio.h>

void main(){

int area = rect_Area();


printf("The area of the Rectangle is: %d\n",area);

int rect_Area(){

int len, wid;

printf("Enter the length of the rectangle: ");

scanf("%d",&len);

printf("Enter the width of the rectangle: ");

scanf("%d",&wid);

return len * wid;

Output:

C programming Functions With Arguments But No Return Value

C functions may accept arguments but not provide any return value. Given below is an
example of such a function.

#include<stdio.h>

void main(){

int x,y;
printf("Enter the two numbers to add:");

scanf("%d %d",&x,&y);

add(x,y);

// Accepting arguments with void return type

void add(int x, int y){

printf("The sum of the numbers is %d",x+y);

Output:

C Programming Functions That Accept Arguments and Give a Return Value

Most C functions will accept arguments and provide a return value. The following program
demonstrates a function in C programming that takes arguments and returns a value.

#include<stdio.h>

void main(){

int x,y,res;

printf("Enter the two numbers to add:");

scanf("%d %d",&x,&y);

res = add(x,y);
printf("The sum of the numbers is %d",res);

int add(int x, int y){

return x+y;

Output:

Get the IIT-M Advantage!

PCP In Full Stack Development - MERNEXPLORE COURSE

More About Functions in C Programming

 Every program in C has a function. Even if you do not use a library or user-defined function, you
will have to use the main function. The main function is the program’s entry point, as that is
where the compiler will start executing the code.

 Even if a function does not return a value, it has a return type. If a return value is provided, the
return type is the data type of the value. But if there is no return value, then the void is the
return type of the function.

 C functions cannot return array and function types. However, you can easily overcome this
limitation with the use of pointers.

 While in C++, void func() and void func(void) mean the same; it is not the case with C
programming. In C, a function declared without any parameter list can be called with any number
of parameters. Hence, it is advisable to declare a function as void func(void) and not void func() if
you want to call a function without any parameter.
 If you call a function before the declaration, the C compiler will by default consider the return
type to be int and show an error if the data type of the return value is anything except int.

Key Function in C Programming

You would have noticed that we have declared a function named main() in every example
that we have seen in this article. In fact, not just this article, every C program that you see
will have a main function. The main function in C programming is a special type of function
that serves as the entry point of the program where the execution begins. By default, the
return type of the main function is int. There can be two types of main() functions: with and
without parameters.

Main function without parameters:

int main(){

… //statements

return 0;

Main function with parameters:

int main(int argc, char * const argv[]){

… //statements

return 0;

Note: We can write a program without the main function, but it is a frowned-upon practice. It
is always best to use the main function for ease of readability and to understand the program.

Recursive Functions in C Programming


Functions in C programming are recursive if they can call themselves until the exit condition
is satisfied. If a function allows you to call itself within the definition in a C program, it is a
recursive function. These functions run by stacking the calls until the exit condition is met
and the flow of the program exits the function. Suppose you want to find the factorial of a
number in C; you can use a recursive function to get the result. Here’s an example to find the
factorial of 8.

#include <stdio.h>

int fact(int num);

int main(){

int i = 8;

printf("The factorial of %d is: %d\n", i, fact(i));

return 0;

int fact(int num){

if (num == 1)

// Exiting condition

return (1);

else

return (num * fact(num - 1));

Output:
Let’s calculate the factorial of 8 and confirm if the output is true. The factorial of the number
is calculated as fact(n) = n * (n-1) * (n-2) * … 1. Hence, the factorial of 8 is
8*7*6*5*4*3*2*1 = 40320. This confirms that our recursive function worked correctly.

Inline Functions in C Programming

While using functions in C programming, the pointer for execution flow jumps to the
function definition after the function call. Hence, an additional pointer is required that goes to
the definition and then returns. However, we can avoid the use of extra pointer by using
inline functions.

Inline functions are the functions where instead of calling the function, we replace it with the
actual program code. Thus, the pointer does not have to jump back to the definition. We need
to use the keyword inline before a function to make it an inline function. These functions are
usually used for small computations. Here’s the syntax of an inline function.

inline function_name (){

//function definition

You might also like