Difference between Array and String in C
×


Difference between Array and String in C

41

Array

Definition and Properties:

An array in C is a grouping of elements sharing the same data type, stored consecutively in memory.

Arrays are declared with a fixed size, and each element can be accessed using an index ranging from 0 to the size of the array minus one.


Size and Memory Allocation:

The dimension of an array is established during compilation and remains immutable throughout program execution.

Memory for an array is allocated either on the stack or heap, depending on its declaration.


Accessing and Manipulating Elements:

Elements of an array are accessed and manipulated using their indices.

Values of array elements can be changed directly using assignment statements or pointer arithmetic.


Null Termination:

Arrays do not require null termination, as they can store any type of data, including binary and non-printable characters.

String

Definition and Properties:

A string in C is a sequence of characters terminated by a null character ('\0').

Strings are represented as arrays of characters, with the last element being the null character.


Size and Memory Allocation:

The size of a string can vary, as it depends on the number of characters it contains.

Memory for strings can be allocated statically (with a fixed size) or dynamically (using pointers and memory allocation functions).


Accessing and Manipulating Elements:

Characters in a string are accessed and manipulated similarly to array elements, using indices.

However, strings in C are immutable, meaning individual characters cannot be changed directly.


Null Termination:

Strings must be null-terminated, with a null character ('\0') indicating the end of the string.

Null termination is essential for string handling functions to determine the end of the string.


Example:

// Program for array and string in C
 #include<stdio.h>
 int main() 
 { 
	 int arr[5] = {1, 2, 3, 4, 5};
	 char str[] = "hello"; 
	 printf("Third element of the array: %d\n", arr[2]);
	 printf("Third character of the string: %c\n", str[2]);
	 arr[2] = 10; 
	 printf("different value of the 3rd element array: %d\n", arr[2]); str[2] = 'L';
	 printf("New value of the third character of the string: %c\n", str[2]); 
	 return 0;
}

Output:

Third element of the array: 3
Third character of the string: l
different value of the 3rd element array: 10
New value of the third character of the string: L


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments