Difference Between Array and String in C
Difference Between Array and String in C
Difference Between Array and String in C
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.
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.
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:
The compiler allocates six bytes of memory in this example for keeping the string
"hello" (five characters plus the null character).
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().
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.
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:
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.
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!
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
Call a Function
Declared functions are not executed immediately. They are "saved for later
use", and will be executed when they are called.
Example
Inside main, call myFunction():
// Create a function
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction(); // call the function
return 0;
}
Try it Yourself »
Example
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
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
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.
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
// Function definition
if (i > j)
return i;
else
return j;
int main(void){
// Calling the function to find the greater number among the two
return 0;
}
Types of Functions in C Programming
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.
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
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>
printf("Welcome to ");
printName();
void printName(){
printf("Simplilearn");
Output:
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 rect_Area(){
scanf("%d",&len);
scanf("%d",&wid);
Output:
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);
Output:
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;
scanf("%d %d",&x,&y);
res = add(x,y);
printf("The sum of the numbers is %d",res);
return x+y;
Output:
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.
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.
int main(){
… //statements
return 0;
… //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.
#include <stdio.h>
int main(){
int i = 8;
return 0;
if (num == 1)
// Exiting condition
return (1);
else
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.
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.
//function definition