C Char Array Assignment: Methods & Examples

There are various ways to assign values to a char array in the C language. Here are some common methods:

  1. Assigning a string literal: You can directly assign a string literal to a char array. For example:
char str1[] = "Hello, world!";
  1. Copying using the strcpy function: You can use the strcpy function to copy a string to a char array. Before using the strcpy function, make sure to include the header file. For example:
#include <string.h>

char str2[20]; // 假设数组大小为20
strcpy(str2, "Hello, world!");
  1. Assigning values using characters: You can assign values to a char array character by character. For example:
char str3[14];
str3[0] = 'H';
str3[1] = 'e';
str3[2] = 'l';
str3[3] = 'l';
str3[4] = 'o';
str3[5] = ',';
str3[6] = ' ';
str3[7] = 'w';
str3[8] = 'o';
str3[9] = 'r';
str3[10] = 'l';
str3[11] = 'd';
str3[12] = '!';
str3[13] = '\0'; // 字符串以null字符结尾

  1. You can use an array initializer to assign values: You can directly initialize a char array using an array initializer. For example:
char str4[] = {'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\0'};

No matter which method is used, it is important to ensure that the char array has enough size to accommodate the string, including the ending null character.

bannerAds