JIYIK CN >

Current Location:Home > Learning > PROGRAM > C语言 >

Initializing character array in C

Author:JIYIK Last Updated:2025/04/17 Views:

This article will demonstrate various ways of initializing a character array in C language.


{}Initializing a character array in C using curly brace list notation

Character arrays are mostly declared as a fixed-size structure and are often initialized immediately. The brace list notation is one of the available ways to initialize a character array with a constant value. You can specify only some of the elements enclosed in the braces because the rest of the character array is implicitly initialized with a null byte value. This is useful if you need to print a character array as a string. Since there is guaranteed to be a null byte character at the end of the valid characters, you can effectively use printfthe functions and %sformat string specifiers to output the contents of the array.

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

void printCharArray(char *arr, size_t len)
{
    printf("arr: ");
    for (int i = 0; i < len; ++i) {
        printf("%c, ", arr[i]);
    }
    printf("\n");
}

enum {LENGTH = 21, HEIGHT = 5};

int main(){
    char c_arr[LENGTH] = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
    printCharArray(c_arr, LENGTH);

    exit(EXIT_SUCCESS);
}

Output:

arr: a, b, c, d, e, f, g, , , , , , , , , , , , , , ,

Using string assignment to initialize character array in C

Another useful way to initialize a character array is to specify a string value in the declaration statement. The number of characters in the string should be less than the length of the array; otherwise, only part of the string will be stored and there will be no terminating null character at the end of the buffer. Therefore, if the user tries %sto print the contents of the array with the specifier, it may access the memory area after the last character and may throw a fault.

Note c_arrthat is 21 characters long and is initialized to a 20 charlong string. Therefore, the 21st character in the array is guaranteed to be \0a byte, making the contents a valid string.

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

void printCharArray(char *arr, size_t len)
{
    printf("arr: ");
    for (size_t i = 0; i < len; ++i) {
        printf("%c, ", arr[i]);
    }
    printf("\n");
}

enum {LENGTH = 21, HEIGHT = 5};

int main(){
    char c_arr[LENGTH] = "array initialization";
    char c_arr2[LENGTH] = "array initialization.f";
    printCharArray(c_arr, LENGTH);
    printCharArray(c_arr2, LENGTH);
    printf("%s\n", c_arr);
    printf("%s\n", c_arr2);

    exit(EXIT_SUCCESS);
}

Output:

arr: a, r, r, a, y,  , i, n, i, t, i, a, l, i, z, a, t, i, o, n,  ,
arr: a, r, r, a, y,  , i, n, i, t, i, a, l, i, z, a, t, i, o, n, .,
array initialization
array initialization.//garbage values//

{{ }}Initializing 2D character array in C using double curly braces

Brace lists can also be used to initialize two-dimensional character arrays. In this example, we declare a 5x5 character array and enclose five braces in outer braces. Note that each string literal in this example initializes five rows of the matrix. The contents of this two-dimensional array cannot %sbe printed with the specifier because the length of each row matches the length of the string literal; therefore, no terminating null byte is implicitly stored during initialization. Normally, the compiler issues a warning if the length of the string is greater than the number of rows in the array.

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

enum {LENGTH = 5, HEIGHT = 5};

int main(){
    char c_arr[HEIGHT][HEIGHT] = { {"hello"}, {"there"}, {"multi"}, {"dimen"}, {"sion."} };

    for (size_t i = 0; i < HEIGHT; ++i) {
        for (size_t j = 0; j < HEIGHT; ++j) {
            printf("%c, ", c_arr[i][j]);
        }
        printf("\n");
    }
    printf("\n");

    exit(EXIT_SUCCESS);
}

Output:

h, e, l, l, o,
t, h, e, r, e,
m, u, l, t, i,
d, i, m, e, n,
s, i, o, n, .,

Previous: None

Next:Clearing a character array in C

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Flushing stdout output stream in C

Publish Date:2025/04/17 Views:200 Category:C语言

stdout This article will demonstrate various methods on how to flush an output stream in C language . Use function in C language fflush to refresh stdout output stream I/O The C standard library provides a stdio buffered version of the I/O

Using the feof function in C language

Publish Date:2025/04/17 Views:87 Category:C语言

feof This article will introduce several ways to use functions in C language . Use feof the function to check the end-of-file indicator on a file stream in C language feof The function is part of the C standard input/output library and is d

Use the C language setenv function to access environment variables

Publish Date:2025/04/17 Views:122 Category:C语言

setenv This article will introduce several methods of using functions to export environment variables in C language . setenv Use function to export environment variables in C language Every program running on a Unix-base system has an envir

How to get the size of an array in C

Publish Date:2025/04/17 Views:62 Category:C语言

This tutorial explains how to determine the length of an array in C. sizeof() The operator is used to get the size/length of an array. sizeof() Operator determines the size of an array in C sizeof() The operator is a compile time unary oper

Initialize array to 0 in C

Publish Date:2025/04/17 Views:133 Category:C语言

This article explains how to initialize an array to 0 in C language. The declaration of an array in C language is as follows. char ZEROARRAY[ 1024 ]; It becomes all zeros at runtime in the global scope. If it is a local array, there is a si

Structure arrays in C

Publish Date:2025/04/17 Views:188 Category:C语言

This tutorial explains how to create a structure array in C language, which is a collection of multiple structure variables, each of which contains information about a different entity. Structure arrays in C An array is a sequential collect

Printing Character Array in C

Publish Date:2025/04/17 Views:106 Category:C语言

This article will introduce various methods on how to print character array in C language. for How to use loop to print character array in C language If we want to print array elements individually and format the output with more details, f

Clearing a character array in C

Publish Date:2025/04/17 Views:119 Category:C语言

This article will introduce several methods to clear character arrays in C language. memset Use function to clear char array in C language memset The _set_storage_region function is commonly used to set a storage area to a constant value. T

在C中将整数转换为字符

Publish Date:2024/01/03 Views:135 Category:C语言

本教程介绍了在C中将整数转换为字符的不同方法。在C编程语言中,将整数转换为字符在各种情况下都很重要。在C中,字符是以ASCII值表示的,因此转换过程相对简单。

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial