Array, Pointer and String
5.1 Concept of array
Concept of Array in C
An array in C is a data structure that stores a fixed-size sequential collection of elements of the same type. Arrays are used to group related variables under a single name and access them using an index.
Key Concepts of Arrays
- Declaration and Initialization:
- Declaration: Specifies the array’s type and size.
- Initialization: Assigns values to the array elements.
- Indexing:
- Zero-based Indexing: Array indices start from 0. The first element is accessed with index 0, the second with index 1, and so on.
- Accessing Elements:
- Elements are accessed using the array name followed by an index in square brackets.
- Multidimensional Arrays:
- Arrays can have more than one dimension, allowing the creation of matrices or tables.
- Memory Allocation:
- Arrays are allocated contiguously in memory. This means that elements are stored next to each other.
Array Declaration and Initialization
- Single-Dimensional Array:
- Declaration:
int arr[5]; // Declares an array of 5 integers
- Initialization:
int arr[5] = {1, 2, 3, 4, 5}; // Initializes the array with values
- Multi-Dimensional Array:
- Declaration:
int matrix[3][4]; // Declares a 2D array with 3 rows and 4 columns
- Initialization:
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
Examples
- Single-Dimensional Array Example:
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
printf(“Element at index %d: %d\n”, i, arr[i]);
}
return 0;
}
Explanation:
- The
arr
array stores 5 integers.
- A
for
loop is used to access and print each element.
- Multi-Dimensional Array Example:
#include <stdio.h>
int main() {
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf(“Element at [%d][%d]: %d\n”, i, j, matrix[i][j]);
}
}
return 0;
}
Explanation:
- The
matrix
array represents a 2D array (2 rows and 3 columns).
- Nested
for
loops are used to access and print each element.
Array Operations
- Traversal: Accessing each element of the array in sequence.
- Insertion: Adding elements at specific positions (for dynamic arrays).
- Deletion: Removing elements and shifting others (for dynamic arrays).
- Searching: Finding an element in the array.
- Sorting: Arranging elements in a specific order (e.g., ascending or descending).
Limitations of Arrays
- Fixed Size: The size of an array must be known at compile time and cannot be changed during runtime.
- Memory Usage: Large arrays can consume a lot of memory.
- No Built-In Bounds Checking: Accessing elements out of the array’s bounds can lead to undefined behavior.
5.2 Array declare, access and initialization.
Array Declaration, Access, and Initialization in C
Arrays are fundamental in C for managing collections of related data. Understanding how to declare, access, and initialize arrays is essential for effective programming.
1. Array Declaration
Declaration specifies the type of elements and the size of the array.
Syntax:
type
: The data type of the array elements (e.g., int
, float
, char
).
arrayName
: The name of the array.
size
: The number of elements the array can hold.
Examples:
- Integer Array:
int numbers[5]; // Declares an array of 5 integers
- Character Array:
char letters[10]; // Declares an array of 10 characters
3.Float Array:
float prices[3]; // Declares an array of 3 floats
2. Array Initialization
Initialization assigns values to array elements at the time of declaration.
Syntax:
type arrayName[size] = {value1, value2, …, valueN};
- If fewer values are provided than the size, the remaining elements are initialized to zero (for numeric types) or null (
\0
) for characters.
Examples:
- Integer Array Initialization:
int numbers[5] = {1, 2, 3, 4, 5}; // Initializes with 5 values
If you omit the size:
int numbers[] = {1, 2, 3, 4, 5}; // Size is determined automatically
2.Character Array Initialization:
char letters[5] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’};
For strings:
char greeting[] = “Hello”; // Initializes with “Hello” and adds null terminator
- Float Array Initialization:
float prices[3] = {10.5, 20.0, 30.75};
3. Array Access
Accessing Elements:
- Elements of an array are accessed using the index (starting from 0).
Syntax:
Examples:
- Accessing an Element:
int numbers[5] = {1, 2, 3, 4, 5};
int value = numbers[2]; // Accesses the element at index 2 (value is 3)
- Modifying an Element:
numbers[1] = 10; // Changes the element at index 1 to 10
- Using Loops:
int i;
for (i = 0; i < 5; i++) {
printf(“Element at index %d: %d\n”, i, numbers[i]);
}
4. Multi-Dimensional Arrays
Declaration and Initialization:
- Two-Dimensional Array:
int matrix[3][4]; // Declares a 2D array with 3 rows and 4 columns
Initialization:
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
- Accessing Elements:
int value = matrix[1][2]; // Accesses the element at row 1, column 2 (value is 6)
Using Nested Loops:
int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
printf(“Element at [%d][%d]: %d\n”, i, j, matrix[i][j]);
}
}
5.3 multi-dimensional array
A multi-dimensional array is an array of arrays. It extends the concept of a one-dimensional array to multiple dimensions, such as 2D matrices or 3D tables. Multi-dimensional arrays are useful for representing complex data structures like grids, tables, or matrices.
1. Declaration
To declare a multi-dimensional array, you specify the number of elements in each dimension.
Syntax:
type arrayName[size1][size2]…[sizeN];
type
: Data type of the array elements.
arrayName
: The name of the array.
size1
, size2
, …, sizeN
: The sizes of each dimension.
Examples:
- Two-Dimensional Array:
int matrix[3][4]; // Declares a 2D array with 3 rows and 4 columns
- Three-Dimensional Array:
int tensor[2][3][4]; // Declares a 3D array with 2 layers, 3 rows, and 4 columns
2. Initialization
Syntax:
type arrayName[size1][size2]…[sizeN] = { { {value1, value2, …}, {…} }, {…} };
- Values for each dimension are enclosed in braces
{}
.
Examples:
- Two-Dimensional Array Initialization:
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
- Three-Dimensional Array Initialization:
int tensor[2][2][3] = {
{ {1, 2, 3}, {4, 5, 6} },
{ {7, 8, 9}, {10, 11, 12} }
};
3. Accessing Elements
Elements in multi-dimensional arrays are accessed using multiple indices.
Syntax:
arrayName[index1][index2]…[indexN]
Examples:
- Accessing 2D Array Elements:
int value = matrix[1][2]; // Accesses the element at row 1, column 2 (value is 6)
- Accessing 3D Array Elements:
int value = tensor[1][0][2]; // Accesses the element at layer 1, row 0, column 2 (value is 9)
4. Using Loops with Multi-Dimensional Arrays
Two-Dimensional Arrays:
#include <stdio.h>
int main() {
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf(“Element at [%d][%d]: %d\n”, i, j, matrix[i][j]);
}
}
return 0;
}
Three-Dimensional Arrays:
#include <stdio.h>
int main() {
int tensor[2][2][3] = {
{ {1, 2, 3}, {4, 5, 6} },
{ {7, 8, 9}, {10, 11, 12} }
};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 3; k++) {
printf(“Element at [%d][%d][%d]: %d\n”, i, j, k, tensor[i][j][k]);
}
}
}
return 0;
}
5.4 Concept of Pointer
A pointer is a variable that stores the memory address of another variable. Pointers are a powerful feature in C, enabling direct memory manipulation and dynamic memory management. Understanding pointers is crucial for advanced C programming tasks, including data structures, dynamic allocation, and system-level programming.
1. Basic Concept
- Definition: A pointer holds the address of a variable rather than the variable’s value.
- Syntax:
Examples:
int *ptr; // Declares a pointer to an integer
2. Pointer Declaration and Initialization
- Declaration: Specifies the type of data the pointer will point to.
- Initialization: Assigns the address of a variable to the pointer.
Examples:
int x = 10; // An integer variable
int *ptr = &x; // Pointer ptr now holds the address of x
Explanation:
int *ptr
: Declares ptr
as a pointer to an int
.
&x
: The address-of operator (&
) gives the memory address of x
.
3. Dereferencing Pointers
- Dereferencing: Accessing the value stored at the address pointed to by the pointer.
- Syntax:
Examples:
int x = 10;
int *ptr = &x;
printf(“Value of x: %d\n”, *ptr); // Dereferencing ptr to get the value of x
Explanation:
*ptr
: Accesses the value at the address stored in ptr
.
4. Pointer Arithmetic
Pointers can be incremented or decremented to navigate through memory addresses.
- Increment: Moves to the next memory location of the pointer type.
- Decrement: Moves to the previous memory location.
Examples:
int arr[3] = {1, 2, 3};
int *ptr = arr;
printf(“First element: %d\n”, *ptr); // Outputs 1
ptr++; // Moves to the next integer location
printf(“Second element: %d\n”, *ptr); // Outputs 2
Explanation:
ptr++
: Advances the pointer to the next integer (4 bytes ahead).
5. Null Pointer
A null pointer is a pointer that points to nothing, represented by NULL
or 0
.
Examples:
int *ptr = NULL; // Initializes pointer to NULL
if (ptr == NULL) {
printf(“Pointer is null\n”);
}
Explanation:
NULL
: A constant defined in <stddef.h>
representing a null pointer.
6. Pointers and Arrays
- Pointer Arithmetic: Arrays and pointers are closely related; array names are pointers to the first element.
- Accessing Array Elements:
int arr[3] = {1, 2, 3};
int *ptr = arr; // Equivalent to int *ptr = &arr[0];
printf(“First element: %d\n”, *ptr); // Outputs 1
printf(“Second element: %d\n”, *(ptr + 1)); // Outputs 2
7. Function Pointers
Pointers can also point to functions, allowing dynamic function calls.
Syntax:
returnType (*functionPointerName)(parameterTypes);
Examples:
#include <stdio.h>
// Function declaration
void sayHello() {
printf(“Hello, world!\n”);
}
int main() {
void (*funcPtr)() = sayHello; // Pointer to function
funcPtr(); // Calling the function via pointer
return 0;
}
Explanation:
void (*funcPtr)()
: Declares a pointer to a function returning void
and taking no parameters.
8. Dynamic Memory Allocation
Pointers are used for dynamic memory allocation with functions such as malloc()
, calloc()
, and free()
.
Examples:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = (int *)malloc(3 * sizeof(int)); // Allocates memory for 3 integers
if (arr == NULL) {
printf(“Memory allocation failed\n”);
return 1;
}
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
for (int i = 0; i < 3; i++) {
printf(“Element %d: %d\n”, i, arr[i]);
}
free(arr); // Frees allocated memory
return 0;
}
Explanation:
malloc()
: Allocates a block of memory and returns a pointer to it.
free()
: Deallocates previously allocated memory.
5.5 Pointer address, dereference, declaration, assignment,
initialization
Pointers in C are variables that store memory addresses of other variables. Understanding how to work with pointers involves concepts such as pointer address, dereferencing, declaration, assignment, and initialization.
1. Pointer Declaration
Declaration of a pointer specifies the type of data the pointer will point to.
Syntax:
type
: The data type of the variable that the pointer will point to.
pointerName
: The name of the pointer variable.
Examples:
int *ptr; // Pointer to an integer
char *cptr; // Pointer to a character
float *fptr; // Pointer to a float
2. Pointer Initialization
Initialization involves assigning the address of a variable to a pointer.
Syntax:
pointerName = &variableName;
&variableName
: The address-of operator (&
) retrieves the memory address of variableName
.
Examples:
int x = 10;
int *ptr = &x; // Initializes ptr with the address of x
Explanation:
ptr
now points to the address of x
.
3. Pointer Address
The address stored in a pointer is the location of a variable in memory.
Syntax:
Examples:
int x = 10;
int *ptr = &x;
printf(“Address of x: %p\n”, (void *)ptr); // %p format specifier prints the address
Explanation:
%p
is used to print the address stored in a pointer.
4. Dereferencing Pointers
Dereferencing a pointer accesses the value stored at the address that the pointer points to.
Syntax:
*pointerName
: The dereference operator (*
) accesses the value at the address contained in pointerName
.
Examples:
int x = 10;
int *ptr = &x;
printf(“Value at ptr: %d\n”, *ptr); // Dereferences ptr to get the value of x
Explanation:
*ptr
retrieves the value of x
through the pointer ptr
.
5. Pointer Assignment
Assignment involves setting a pointer to point to the address of a variable.
Syntax:
pointerName = &variableName;
Examples:
int x = 10;
int y = 20;
int *ptr;
ptr = &x; // ptr now points to x
ptr = &y; // ptr now points to y
Explanation:
- The pointer
ptr
can be reassigned to point to different variables.
6. Putting It All Together
Here’s a complete example demonstrating declaration, initialization, address retrieval, dereferencing, and assignment:
Example Code:
#include <stdio.h>
int main() {
int x = 10; // Regular variable
int *ptr; // Pointer declaration
ptr = &x; // Pointer initialization with the address of x
// Display address and value
printf(“Address of x: %p\n”, (void *)ptr); // Pointer address
printf(“Value at ptr: %d\n”, *ptr); // Dereferencing the pointer
int y = 20;
ptr = &y; // Reassign pointer to point to y
// Display new address and value
printf(“Address of y: %p\n”, (void *)ptr); // New pointer address
printf(“Value at ptr: %d\n”, *ptr); // Dereferencing the new pointer
return 0;
}
Explanation:
- Pointer
ptr
is first initialized to point to x
, then reassigned to point to y
.
- Address and values are printed using the pointer.
5.6 Pointer Arithmetic
Pointer arithmetic involves operations on pointers that allow you to navigate through memory locations. This can be useful for traversing arrays or managing dynamic memory. Here’s a detailed look at how pointer arithmetic works in C.
1. Basic Pointer Arithmetic Operations
- Increment and Decrement:
- Increment (
++
): Moves the pointer to the next memory location of its type.
- Decrement (
--
): Moves the pointer to the previous memory location of its type.
Syntax:
Examples:
int arr[3] = {10, 20, 30};
int *ptr = arr; // Pointer to the first element of the array
printf(“Value at ptr: %d\n”, *ptr); // Outputs 10
ptr++; // Moves to the next integer location
printf(“Value at ptr: %d\n”, *ptr); // Outputs 20
Explanation:
ptr++
advances the pointer by sizeof(int)
bytes (usually 4 bytes), so it now points to arr[1]
.
- Addition and Subtraction:
- Addition (
+
): Moves the pointer forward by a number of elements.
- Subtraction (
-
): Moves the pointer backward by a number of elements.
Syntax:
pointer + n; // Moves pointer forward by n elements
pointer – n; // Moves pointer backward by n elements
Examples:
int arr[4] = {1, 2, 3, 4};
int *ptr = arr;
printf(“Value at ptr + 2: %d\n”, *(ptr + 2)); // Outputs 3
printf(“Value at ptr – 1: %d\n”, *(ptr – 1)); // Undefined behavior, ptr – 1 is outside array bounds
Explanation:
ptr + 2
advances the pointer by 2 elements (so it points to arr[2]
).
2. Pointer Comparison
Pointers can be compared using relational operators.
- Equal (
==
): Checks if two pointers point to the same location.
- Not Equal (
!=
): Checks if two pointers point to different locations.
- Less Than (
<
): Checks if a pointer points to a location before another pointer.
- Greater Than (
>
): Checks if a pointer points to a location after another pointer.
- Less Than or Equal (
<=
): Checks if a pointer is before or at the same location as another pointer.
- Greater Than or Equal (
>=
): Checks if a pointer is after or at the same location as another pointer.
Examples:
int arr[3] = {10, 20, 30};
int *ptr1 = &arr[0];
int *ptr2 = &arr[2];
if (ptr1 < ptr2) {
printf(“ptr1 points to an earlier location than ptr2\n”);
}
Explanation:
ptr1 < ptr2
checks if ptr1
points to a lower memory address than ptr2
.
3. Pointer Arithmetic with Arrays
Arrays and pointers are closely related; the name of an array is a pointer to its first element. Pointer arithmetic can be used to traverse arrays efficiently.
Example:
#include <stdio.h>
int main() {
int arr[4] = {1, 2, 3, 4};
int *ptr = arr; // Equivalent to int *ptr = &arr[0];
for (int i = 0; i < 4; i++) {
printf(“Element %d: %d\n”, i, *(ptr + i)); // Access array elements using pointer arithmetic
}
return 0;
}
Explanation:
*(ptr + i)
accesses the i-th element of the array, leveraging pointer arithmetic.
4. Pointer Arithmetic with Structs
Pointers can be used with structs, and pointer arithmetic can navigate through arrays of structs.
Example:
#include <stdio.h>
typedef struct {
int id;
char name[20];
} Student;
int main() {
Student students[3] = {{1, “Alice”}, {2, “Bob”}, {3, “Charlie”}};
Student *ptr = students; // Pointer to the first element of the array of structs
for (int i = 0; i < 3; i++) {
printf(“Student %d: %d, %s\n”, i + 1, (ptr + i)->id, (ptr + i)->name);
}
return 0;
}
Explanation:
(ptr + i)->id
accesses the id
field of the i-th Student
in the array.
5.7 Array and Pointer
Arrays and pointers are fundamental concepts in C programming that are closely related. Understanding their relationship helps with efficient memory management and manipulation of data structures.
1. Array Overview
An array is a collection of elements of the same type stored in contiguous memory locations. The array name represents a pointer to the first element of the array.
Syntax:
Examples:
int arr[5]; // Declares an array of 5 integers
char str[10]; // Declares an array of 10 characters
2. Pointer Overview
A pointer is a variable that holds the memory address of another variable. Pointers can be used to reference array elements, traverse arrays, and perform dynamic memory allocation.
Syntax:
Examples:
int *ptr; // Pointer to an integer
char *cptr; // Pointer to a character
3. Relationship Between Arrays and Pointers
- Array Name as Pointer: The name of an array acts as a pointer to its first element.
- Pointer Arithmetic: Pointers can be used to navigate through array elements.
Examples:
int arr[3] = {1, 2, 3};
int *ptr = arr; // Equivalent to int *ptr = &arr[0];
Explanation:
ptr
points to the first element of arr
.
4. Accessing Array Elements with Pointers
You can use pointers to access and manipulate array elements.
Syntax:
Examples:
#include <stdio.h>
int main() {
int arr[3] = {10, 20, 30};
int *ptr = arr; // Pointer to the first element of the array
printf(“First element: %d\n”, *ptr); // Outputs 10
printf(“Second element: %d\n”, *(ptr + 1)); // Outputs 20
printf(“Third element: %d\n”, *(ptr + 2)); // Outputs 30
return 0;
}
Explanation:
*ptr
dereferences the pointer to get the value of the first element.
*(ptr + 1)
accesses the second element, and so on.
5. Array and Pointer Arithmetic
You can perform arithmetic operations on pointers to traverse arrays.
Examples:
#include <stdio.h>
int main() {
int arr[4] = {1, 2, 3, 4};
int *ptr = arr;
for (int i = 0; i < 4; i++) {
printf(“Element %d: %d\n”, i, *(ptr + i));
}
return 0;
}
Explanation:
ptr + i
moves the pointer to the i-th element of the array.
6. Passing Arrays to Functions
When passing arrays to functions, you actually pass pointers to the first element of the array.
Syntax:
void functionName(type *arrayName);
Examples:
#include <stdio.h>
void printArray(int *arr, int size) {
for (int i = 0; i < size; i++) {
printf(“%d “, *(arr + i));
}
printf(“\n”);
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
printArray(arr, 5); // Passing array to function
return 0;
}
Explanation:
printArray
function receives a pointer to the first element of the array and its size.
7. Dynamic Memory Allocation with Pointers
Pointers are used with dynamic memory allocation functions to create arrays whose size can be determined at runtime.
Examples:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
int size = 5;
arr = (int *)malloc(size * sizeof(int)); // Allocates memory for an array of 5 integers
if (arr == NULL) {
printf(“Memory allocation failed\n”);
return 1;
}
for (int i = 0; i < size; i++) {
arr[i] = i + 1; // Initialize array
}
for (int i = 0; i < size; i++) {
printf(“%d “, *(arr + i)); // Print array elements
}
free(arr); // Free allocated memory
return 0;
}
Explanation:
malloc
allocates memory dynamically.
free
deallocates the memory when it is no longer needed.
5.7 Array and Pointer
Arrays and pointers are closely related concepts in C programming. They both involve managing collections of data and accessing memory locations. Here’s an in-depth look at how arrays and pointers are interrelated and how they can be used together effectively.
1. Arrays
An array is a collection of elements of the same type stored in contiguous memory locations.
Declaration and Initialization:
Examples:
int arr[5]; // Array of 5 integers
float prices[3] = {10.5, 20.75, 30.0}; // Array of 3 floats initialized
char name[10] = “Alice”; // Array of 10 characters (string)
arr[0]
: First element.
arr[4]
: Fifth element.
Accessing Elements:
- Using Index:
arr[index]
- Using Pointers:
*(ptr + index)
2. Pointers
A pointer is a variable that stores the memory address of another variable.
Declaration and Initialization:
type *pointerName;
pointerName = &variable;
Examples:
int x = 10;
int *ptr = &x; // Pointer to the integer variable x
*ptr
: Dereferences the pointer to access the value of x
.
3. Relationship Between Arrays and Pointers
- Array Name as Pointer: The name of an array is a pointer to its first element.
Example:
int arr[3] = {1, 2, 3};
int *ptr = arr; // Equivalent to int *ptr = &arr[0];
- Accessing Array Elements with Pointers:
printf(“%d\n”, *(ptr + 0)); // Outputs 1
printf(“%d\n”, *(ptr + 1)); // Outputs 2
printf(“%d\n”, *(ptr + 2)); // Outputs 3
4. Pointer Arithmetic with Arrays
You can use pointer arithmetic to navigate through array elements.
Increment and Decrement:
ptr++; // Moves to the next element in the array
ptr–; // Moves to the previous element
Addition and Subtraction:
*(ptr + i) // Accesses the i-th element from the pointer
*(ptr – i) // Accesses the element i positions before the pointer
Example:
int arr[4] = {10, 20, 30, 40};
int *ptr = arr; // Pointer to the first element
printf(“%d\n”, *(ptr + 1)); // Outputs 20
printf(“%d\n”, *(ptr + 2)); // Outputs 30
5. Passing Arrays to Functions
When an array is passed to a function, it is actually passed as a pointer to its first element.
Function Declaration:
void functionName(type *arrayName, int size);
Example:
#include <stdio.h>
void printArray(int *arr, int size) {
for (int i = 0; i < size; i++) {
printf(“%d “, *(arr + i));
}
printf(“\n”);
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
printArray(arr, 5); // Passing array to function
return 0;
}
Explanation:
printArray
function receives a pointer to the array and its size.
6. Dynamic Memory Allocation with Pointers
Pointers are used for dynamic memory allocation, allowing arrays to be created with sizes determined at runtime.
Functions:
malloc(size_t size)
: Allocates a block of memory.
calloc(size_t num, size_t size)
: Allocates memory for an array and initializes it to zero.
realloc(void *ptr, size_t size)
: Resizes a previously allocated block of memory.
free(void *ptr)
: Frees previously allocated memory.
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
int size = 5;
arr = (int *)malloc(size * sizeof(int)); // Allocate memory
if (arr == NULL) {
printf(“Memory allocation failed\n”);
return 1;
}
for (int i = 0; i < size; i++) {
arr[i] = i + 1; // Initialize array
}
for (int i = 0; i < size; i++) {
printf(“%d “, arr[i]); // Print array elements
}
free(arr); // Free allocated memory
return 0;
}
Explanation:
malloc
allocates memory dynamically for the array.
free
deallocates the memory when it is no longer needed.
5.8 String
In C, strings are arrays of characters terminated by a null character ('\0'
). Unlike some other programming languages where strings are treated as a built-in data type, in C, strings are managed using arrays of characters.
1. String Declaration and Initialization
String Declaration:
String Initialization:
Examples:
char greeting[6] = “Hello”; // Array of 6 characters including the null terminator
char name[] = “Alice”; // Automatically allocates 6 characters (5 + null terminator)
Explanation:
"Hello"
includes the null character '\0'
at the end, which signifies the end of the string.
2. Accessing String Characters
You can access individual characters of a string using array indexing.
Syntax:
Examples:
char str[] = “Hello”;
printf(“%c\n”, str[0]); // Outputs ‘H’
printf(“%c\n”, str[4]); // Outputs ‘o’
Explanation:
str[0]
accesses the first character.
str[4]
accesses the fifth character.
3. Common String Functions
The C Standard Library provides several functions for string manipulation in <string.h>
.
strlen(str)
: Returns the length of the string (excluding the null terminator).
strcpy(dest, src)
: Copies the source string to the destination string.
strcat(dest, src)
: Appends the source string to the end of the destination string.
strcmp(str1, str2)
: Compares two strings lexicographically.
Examples:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = “Hello”;
char str2[20] = “World”;
// Length of str1
printf(“Length of str1: %lu\n”, strlen(str1));
// Copy str1 to str2
strcpy(str2, str1);
printf(“str2 after copy: %s\n”, str2);
// Concatenate str1 to str2
strcat(str2, ” World”);
printf(“str2 after concatenation: %s\n”, str2);
// Compare str1 and str2
int result = strcmp(str1, str2);
if (result == 0) {
printf(“str1 and str2 are equal\n”);
} else if (result < 0) {
printf(“str1 is less than str2\n”);
} else {
printf(“str1 is greater than str2\n”);
}
return 0;
}
Explanation:
strlen
gives the length of the string.
strcpy
copies str1
to str2
.
strcat
appends " World"
to str2
.
strcmp
compares str1
and str2
.
4. String Literals
A string literal is a sequence of characters enclosed in double quotes. They are automatically null-terminated.
Example:
char *str = “Hello, World!”;
Explanation:
- The compiler automatically adds the null terminator.
5. String Input and Output
Input:
scanf
can be used to read a string. It stops reading at whitespace.
Examples:
char str[50];
printf(“Enter a string: “);
scanf(“%s”, str); // Reads a string until the first whitespace
Output:
printf
is used to print strings.
Examples:
char str[] = “Hello, World!”;
printf(“%s\n”, str); // Prints the string
6. Strings and Pointers
Strings can be manipulated using pointers. The name of the string is essentially a pointer to the first character.
Example:
#include <stdio.h>
int main() {
char *str = “Hello, Pointer!”;
char *ptr = str;
while (*ptr != ‘\0’) {
printf(“%c”, *ptr);
ptr++;
}
return 0;
}
Explanation:
*ptr
accesses each character in the string, and ptr++
moves the pointer to the next character.
5.9 String functions in C
C provides a rich set of functions for manipulating strings, which are available in the <string.h>
library. These functions are essential for performing various operations on strings, such as copying, concatenation, and comparison. Here’s a comprehensive overview of commonly used string functions: