目录:
- array
- '\0' 与 EOF
array:
参考:C 数组
参考:C 字符串
总结:数组对于数字型和字符型有不同,数字数组就是实际长度,而字符型数组需要增加一个 '\0',所以对于数字数组可以这样定义 int num[] = {1, 2, 3, 4, 5}; ,而字符型数组需要预先定义长度,否则没有 '\0' 会出错,需要这样定义 char str[6] = {'h', 'e', 'l', 'l', 'o'};或者 char str[] = "hello",会自动添加 '\0'。
#include <stdio.h> #include <string.h> int main(void) { char *r = "hello"; char s[10] = {'h','e','l','l','o'}; char ss[] = {'h','e','l','l','o'}; char t[] = "hello"; int num[] = {1, 2, 3, 4, 5}; printf ("r = %s\ns = %s\nss = %s\nt = %s\n", r, s, ss, t); printf ("The length of r is %ld.\n", sizeof(r)); // address printf ("The strlen of r is %ld.\n", strlen(r)); // actual length printf ("The length of s is %ld.\n", sizeof(s)); // s[10] with '\0' printf ("The length of ss is %ld.\n", sizeof(ss)); // print with error printf ("The length of t is %ld.\n", sizeof(t)); // t[6] with '\0' printf ("The strlen of t is %ld.\n", strlen(t)); // actual length printf ("The length of num is %ld.\n", sizeof(num)/sizeof(num[0])); // actual length for (int i = 0; i < sizeof(num)/sizeof(num[0]); i++) { printf("%d\n", num[i]); } /* r = hello*/ /* s = hello*/ /* ss = hellohello ----error----*/ /* t = hello*/ /* The length of r is 8.*/ /* The strlen of r is 5.*/ /* The length of s is 10.*/ /* The length of ss is 5. ----without '\0'----*/ /* The length of t is 6.*/ /* The strlen of t is 5.*/ /* The length of num is 5.*/ /* 1*/ /* 2*/ /* 3*/ /* 4*/ /* 5*/ return 0; }
'\0' 与 EOF 的区别
前者作为字符串的结尾标志
后者作为文件的结尾标志
如下所示:(0,与 -1)
#include <stdio.h> #include <stdlib.h> int main(){ printf("\'\\0\' is %d\n", '\0'); printf("EOF is %d\n", EOF); /* '\0' is 0*/ /* EOF is -1*/ return 0; }