C Arrays ======================================================================================= #include main() { int a[4]; /* a is an address constant (the address of a[0]) */ /* space for four ints (16 or 32 bytes) reserved */ int *pa; /* pa is an address variable that must point to an int */ /* space for a single address (4 or 8 bytes) reserved */ pa = a; /* variable = constant (like i = 1234) */ a[0] = 100; /* array subscripts start a 0 */ *(a+1) = 101; /* *(a+1) same as a[1] */ pa[2] = 102; /* since pa = a, pa[2] = a[2] */ *(pa+3) = 103; /* *(pa+3) == *(a+3) == pa[3] == a[3] so */ /* pa+3 == a+3 == &pa[3] == &a[3] */ } ====================================================================================== 1. Character arrays are simply byte arrays that must include a byte with a value of zero to mark the end of the array. 2. The first eight statements are equivalent. char str[4] = "ABC" /* Need one byte for the terminating zero */ char str[] = "ABC" /* Four bytes reserved and initialized */ char str[4] = {65, 66, 67, 00); /* ASCII codes for A, B, C, an null */ char str[] = {65, 66, 67, 00); /* ASCII codes for A, B, C, and null */ char str[4] = {0x41, 0x42, 0x43, 0x00); /* ASCII codes in hex */ char str[] = {0x41, 0x42, 0x43, 0x00); /* ASCII codes in hex */ char str[] = {'A', 'B', 'C', '\0'); /* Chacter (not string) constant */ char ok[4] = "AB" /* Four bytes reserved, three initialized */ char bad[4] = {65, 66} /* Four bytes reserved, only two initiallized */ char bad[] = {65, 66, 67}; /* Only three reserved, no termination zero */ char bad[4] = {65, 66, 67}; /* Four reserved, but last not initialized */ char bad[3] = "ABC"; /* compiler will catch this */ char bad[4] = 'ABC'; /* and this */ ====================================================================================== cis-lclient03:~/2012/chap2>more strlen1.c /* Compute the length of a string */ #include int strlen(char s[]); int main() { char line[100] = "This length of this string is "; printf("%s%d\n", line, strlen(line)); return 0; } /* strlen: return length of s */ int strlen(char s[]) { int i; i = 0; while (s[i] != '\0') ++i; return i; } cis-lclient03:~/2012/chap2>gcc strlen1.c cis-lclient03:~/2012/chap2>./a.out This length of this string is 30 cis-lclient03:~/2012/chap2> ====================================================================================== /* alternate version of strlen: return length of s */ int strlen(char *s) { int n; for (n = 0; *s != '\0'; s++) n++; return n; } ====================================================================================== /* yet another version of strlen: return length of s */ int strlen(char *s) { char *p = s; while (*p != '\0'); p++; return p - s; } ======================================================================================