What is the difference between array and string in C?
C Programming Language > String in C Language > Introduction to String
1936
Answer:
- Array can hold any of the data types. But, string can hold only char data type.
- Array size must be a constant value. So, array size can’t be changed once declared. But, string size can be modified using char pointer.
- Array is not ended with null character by default. But, string is ended with null (‘\0’) character by default.
Here's a comparison between arrays and strings in C:
Aspect | Array | String |
---|---|---|
Definition | A collection of elements of the same data type. | A sequence of characters terminated by a null character ('\0' ). |
Data Type | Can store elements of any data type (e.g., int, char, etc.). | Specifically stores characters (char type) or an array of characters. |
Initialization | Can be initialized with default values or specific elements. | Can be initialized using string literals or an array of characters. |
Termination | No specific termination character. | Terminated by a null character ('\0' ) to indicate the end of the string. |
Size | Size is determined by the number of elements in the array. | Size is determined by the length of the string, excluding the null terminator. |
Access | Elements accessed using array indexing. | Individual characters can be accessed using array indexing or string manipulation functions. |
Modification | Elements can be modified individually. | Characters within a string can be modified, but the length of the string cannot be changed directly. |
Functions | Array-specific functions can be used for manipulation. | String-specific functions from the C standard library (<string.h> ) can be used for manipulation. |
In summary, an array in C is a collection of elements of the same data type, while a string is a sequence of characters terminated by a null character. Arrays can store elements of any data type, whereas strings specifically store characters or arrays of characters. Strings have a special termination character ('\0'
) to indicate the end of the string. Arrays are accessed and modified using array indexing, while strings can be manipulated using string-specific functions from the C standard library.
This Particular section is dedicated to Question & Answer only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.