C Arrays and Strings
An array stores elements of the same type in contiguous memory. A string in C is a char array terminated by the null character '\0'.
Array: Bubble Sort
#include <stdio.h>
int main() {
int a[] = {64, 25, 12, 22, 11}, n = 5;
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - 1 - i; j++)
if (a[j] > a[j + 1]) {
int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
}
for (int i = 0; i < n; i++) printf("%d ", a[i]);
return 0;
}
11 12 22 25 64
String Functions (string.h)
| Function | Purpose |
|---|---|
strlen(s) | Length (excluding '\0') |
strcpy(d, s) | Copy s into d |
strcat(d, s) | Append s to d |
strcmp(a, b) | 0 if equal, <0 or >0 otherwise |
strrev(s) | Reverse (non-standard, not in GCC) |
#include <stdio.h>
#include <string.h>
int main() {
char s[50] = "Hello";
strcat(s, " World");
printf("%s has %zu chars\n", s, strlen(s));
printf("cmp = %d\n", strcmp("abc", "abc"));
return 0;
}
Hello World has 11 chars
cmp = 0
Track your progress through the C course