Следующий фрагмент кода иллюстрирует все варианты использования строковых констант, массивов и указателей, а также sizeof
и strlen
.
const char *a = "play\n";
const char at[] = "play\n";
int sizeBitA1 = sizeof(a); // 8 bytes == size of a pointer
int sizeBitA2 = sizeof("play\n"); // 6 bytes, including the trailing '\0'
int sizeBitA3 = sizeof(at); // 6 bytes, including the trailing '\0'
int sizeBitA4 = strlen(a); // 5 bytes, excluding the trailing '\0'
int sizeBitA5 = strlen("play\n"); // 5 bytes, excluding the trailing '\0'
int sizeBitA6 = strlen(at); // 5 bytes, excluding the trailing '\0'
const char *b = "\r\n";
const char bt[] = "\r\n";
int sizeBitB1 = sizeof(b); // 8 bytes == size of a pointer
int sizeBitB2 = sizeof("\r\n"); // 3 bytes, including the trailing '\0'
int sizeBitB3 = sizeof(bt); // 3 bytes, including the trailing '\0'
int sizeBitB4 = strlen(b); // 2 bytes, excluding the trailing '\0'
int sizeBitB5 = strlen("\r\n"); // 2 bytes, excluding the trailing '\0'
int sizeBitB6 = strlen(bt); // 2 bytes, excluding the trailing '\0'