C语言字符数组的初始化
要点说明
1 C语言默认会针对全局变量数组执行初始化 初始化的值为字符串结束符‘/0’
2 C语言默认不会对局部变量数组执行初始化
字符数组的初始化方法
1 memset
char local_names2[5];
memset(local_names2, 0, sizeof(local_names2));
2 直接赋值
char local_names1[5]=“”;
char local_names[5]={0};
测试结果
#include <stdio.h>
#include <string.h>
void test_local_char_array3() {
char local_names3[5];
//memset(local_names3, 0, sizeof(local_names3));
for (int i = 0; i < 5; i++) {
printf("%s\n", local_names3[i]);
}
}
void test_local_char_array2() {
char local_names2[5];
memset(local_names2, 0, sizeof(local_names2));
for (int i = 0; i < 5; i++) {
printf("%s\n", local_names2[i]);
}
}
void test_local_char_array1() {
char local_names1[5]="";
for (int i = 0; i < 5; i++) {
printf("%s\n", local_names1[i]);
}
}
void test_local_char_array() {
char local_names[5]={0};
for (int i = 0; i < 5; i++) {
printf("%s\n", local_names[i]);
}
}
int main() {
char names[5];
for (int i = 0; i < 5; i++) {
printf("%s\n", names[i]);
}
printf("-> define local char array and init with '= ""' \n");
test_local_char_array();
printf("-> define local char array1 and init with memset \n");
test_local_char_array1();
printf("-> define local char array2 and init with '={0}' \n");
test_local_char_array2();
printf("-> define local char array3 without init\n");
test_local_char_array3();
return 0;
}
执行结果
(null)
(null)
(null)
(null)
(null)
-> define local char array and init with '= '
(null)
(null)
(null)
(null)
(null)
-> define local char array1 and init with memset
(null)
(null)
(null)
(null)
(null)
-> define local char array2 and init with '={0}'
(null)
(null)
(null)
(null)
(null)
-> define local char array3 without init
(null)
Segmentation fault (core dumped)