这是本文档旧的修订版!
#include <stdio.h> #include <string.h> int main() { char str1[] = "Hello"; char str2[] = "Hello\0"; char str3[] = {'h', 'e', 'l', 'l', 'o', '\0'}; char str4[] = {'h', 'e', 'l', 'l', 'o'}; // 【字符串长度】: printf("%d\n", strlen(str1)); printf("%d\n", strlen(str2)); printf("%d\n", strlen(str3)); printf("%d\n---\n", strlen(str4)); // str4是一个非法字符数组(没有以\0结尾),为未定义(undefined behavior) // 如果强行printf或者strlen,会返回到下一个内存中随机的\0为止! // 【数组长度】: printf("%d\n", sizeof(str1) / sizeof(str1[0])); printf("%d\n", sizeof(str2) / sizeof(str2[0])); printf("%d\n", sizeof(str3) / sizeof(str3[0])); printf("%d\n", sizeof(str4) / sizeof(str4[0])); return 0; } /* 运行情况: 5 5 5 10 --- 6 7 6 5 */