C-Arrays
C-Arrays
Computing Lab
https://www.isical.ac.in/~dfslab
Syntax
char charArray[128], c; // charArray : array of 128 chars
int intArray[64], i, j; // intArray : array of 64 ints
...
charArray[i] = c; // 0 <= i <= 127
intArray[0] = i; j = intArray[63];
Definition
Strings are character arrays, but the end of the string is marked by the
first occurrence of ’\0’ in the array (not the last element of the array)
Example:
1 char str0[8] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };
2 char str1[8] = { 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q' };
3 char str2[8] = { 'z', 'y', 'x', 'w', 'v', 'u', 't', 's' };
4
5 str1[0] = 'a'; str1[1] = 'b'; str1[2] = 'c'; str1[3] = '\0';
6 /* str1 now holds the string "abc" */
1 Try
printf("%s\n", str1);
at lines 4 and 7 in the example code given above.
2 At lines 4 and 7, try
for (i=0; i<8; i++) printf("%c\n", str1[i]);
3 Print str0, str1 and str2 after replacing line 5 by
(a) strcpy(str1, "abc");
(b) strncpy(str1, "abc", j); for j ∈ {0, 1, 2, . . . , 10}.
(c) strncpy(str1, "abcdefgh...xyz", j); for j ∈ {0, 1, 2, . . . , 26}.
Permitted operations
str1 = "Another string"; // change str1 itself
str1++; // move str1 1 char forward (to 'n')
str2a[i] = 'X'; // change elements of string;
// 0 <= i < sizeof(str2a)
strcat(str2b, str1); // strcpy also works
NOT permitted
1 String copying
do {
*s = *t;
s++; t++;
} while (*t != '\0');
1 String copying
do {
*s = *t;
s++; t++;
} while (*t != '\0');
do {
*s++ = *t++;
} while (*t != '\0');
1 String copying
do {
*s = *t;
s++; t++;
} while (*t != '\0');
do {
*s++ = *t++;
} while (*t != '\0');
p = "abcdefghijklmnop\n";
printf(p);
p = "abcdefghijklmnop\n";
printf(p);
p = "abcdefghijklmnop\n";
printf(p + 2);
p = "abcdefghijklmnop\n";
printf(p);
p = "abcdefghijklmnop\n";
printf(p + 2);
p = "abcdefghijklmnop\n";
printf(p + i);