arrays and strings

int ports[] = {22, 80, 443};
size_t count = sizeof ports / sizeof ports[0];

Output value:

3

Array size

sizeof on an array gives bytes Divide by the element size to get the count This only works while the array is still an array, not a decayed pointer

Strings

A C string is a byte array ending in '\0' strlen counts until that byte If the terminator is missing, strlen walks into adjacent memory

Bounded formatting

char buf[64];
int written = snprintf(buf, sizeof buf, "%s:%d", host, port);

Check that written is positive and less than the buffer size A truncated result is not a successful format

Common failure

strcpy and sprintf do not know the destination size Reach for bounded alternatives An unchecked copy is the classic overflow

Next

Pointers in 07 pointers

Posted