Fundamentals of C Language: Arrays and Strings

In the process of learning C language, arrays and strings are among the first concepts we encounter and use most frequently. They are also crucial foundations for subsequent studies in pointers and data structures. Not only are they powerful tools for storing a collection of data of the same type, but they are also essential for text processing, algorithm implementation, and data manipulation.

However, in C language, strings are not an independent data type but exist in the form of character arrays. This design is both flexible and detailed, often causing confusion for beginners. This article will take you deep into understanding the definition and usage of arrays in C language, the relationship between character arrays and strings, common operations, and important considerations, helping you build a solid foundation for future studies in pointers and advanced programming.

1. Arrays

Arrays are collections that store multiple data of the same type. One characteristic is that all elements are stored in contiguous memory locations, allowing access to each element via an index.

1. Declaring Arrays

The index of array elements starts from 0. Therefore, arr[0] is the first element of the array, and arr[4] is the last element.

int arr[5]; // Array to store 5 integers

2. Initializing Arrays

Arrays can be initialized at the time of declaration:

int arr[5] = {1, 2, 3, 4, 5}; // Initializing the array

If not fully initialized, the remaining elements will automatically be assigned a value of 0:

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

3. Accessing Array Elements

To access array elements, use the index:

printf("%d", arr[0]); // Output the first element arr[0] = 10;  // Modify the first element to 10

4. Size of the Array

In C language, there is no direct function to get the size of an array, but you can use sizeof to obtain the size of the array:

int arr[5];printf("Array size: %lu\n", sizeof(arr)); // Output total byte size of the arrayprintf("Array length: %lu\n", sizeof(arr) / sizeof(arr[0])); // Output number of elements in the array

5. Multidimensional Arrays

C language also supports multidimensional arrays, such as two-dimensional arrays (matrices):

int matrix[3][3] = {    {1, 2, 3},    {4, 5, 6},    {7, 8, 9}};

You can access elements of a two-dimensional array using two indices:

printf("%d", matrix[0][0]); // Output 1

2. Strings

In C language, a string is a character array that ends with a \0 (null character) to indicate the end of the string.

1. Declaring and Initializing Strings

char str[6] = "Hello"; // Declare and initialize a string

Here, the str array actually has 6 elements, with the last element being \0.

You can also initialize it character by character:

char str[] = {'H','e','l','l','o','\0'}; // Manually add '\0'

2. Common String Operations

To get the length of a string: use the strlen function.

#include <string.h>int length = strlen(str); // Get the length of the string, excluding '\0'

String copy: use strcpy.

char dest[10];strcpy(dest, str); // Copy the content of str to dest

Concatenating strings: use strcat.

char str1[20] = "Hello,";char str2[] = "World!";strcat(str1, str2); // Concatenate str2 to str1

Comparing strings: use strcmp.

if (strcmp(str1, str2) == 0) {    printf("Strings are the same\n");}else{    printf("Strings are different\n");}

Finding a character: use strchr.

char str[] = "Hello, world!";char *result = strchr(str, 'o'); // Find character oif (result != NULL) {    printf("Position of character o: %ld\n", result - str);}else{    printf("Not found\n");}

Finding a substring: use strstr.

char str[] = "Hello, world!";char *result = strstr(str, "world");if (result != NULL) {    printf("%s\n", result); // Output world}else{    printf("Not found\n");}

Splitting strings: use strtok.

char str[] = "huawei,vivo,xiaomi";char *token = strtok(str, ","); // First delimiter is a commawhile (token != NULL) {    printf("%s\n", token); // Output huawei\nvivo\nxiaomi    token = strtok(NULL, ","); // Get the next substring}

Formatting strings: use sprintf.

char buffer[50];int num = 123;sprintf(buffer, "%d", num); // Write formatted content to bufferprintf("%s\n", buffer); // Output 123

3. Array of Strings

char *arr[] = {"123", "456"};

4. Multidimensional Array of Strings

char arr[2][10] = {"123", "456"}; // Define a two-dimensional array containing 4 strings, each with a maximum of 10 characters

Comrades! Through the study of this article, we have systematically mastered the definition, initialization, and access methods of arrays in C language, and also deeply understood the relationship between character arrays and strings, as well as common string processing functions and operation techniques.

Arrays are the cornerstone of data organization in C language, while strings, as a special type of character array, have wide applications in text processing, user interaction, and file reading and writing. They may seem simple, but they contain many details and techniques, which are key to writing efficient and reliable programs.

I hope you can skillfully use arrays and strings in your future programming practice, gradually cultivating your sensitivity and control over data structures. Remember, a tall building rises from the ground, and arrays and strings are your first step towards more complex algorithms and data structures! Keep it up, comrades!

Leave a Comment