Portál AbcLinuxu, 12. května 2025 05:44
Řešení dotazu:
Nejde. Ale muzete to udelat bud pomoci sizeof, nebo sablon.
#include <iostream> #include <cstddef> template<std::size_t N_> std::size_t length(const char (&s)[N_]) { return N_; } int main(int argc, char** argv) { const char str[] = "Hello World!"; std::cout << sizeof(str) << ", " << length(str) << "\n"; std::cout << sizeof("Hello World!") << ", " << length("Hello World!") << "\n"; return 0; }
(Pozn.: oba dva zpusoby vraceji delku retezce vcetne ukoncovaciho null, tzn. o jednicku vetsi, nez co dava strlen().)
#include <iostream> int main() { char const *x = "Hello world!"; std::cout << x << ", " << sizeof(x) << "\n"; }vypise velikost ukazatele, ne delku retezce!
char
8 bitov.
Prenositelna verzia:
...
const char str[] = "Hello World!";
std::cout << sizeof(str)/sizeof(*str) << ", " << length(str) << "\n";
...
$ cat ll.c
#include <string.h>
#define STRLEN(x) strlen(x)
int main() {
return STRLEN("rozedeleny retezec" "neurcite delky");
}
$ ~/src/llvm/Debug/bin/clang -O2 -S ll.c -o -
.file "ll.c"
.text
.globl main
.align 16, 0x90
.type main,@function
main:
pushl %ebp
movl %esp, %ebp
movl $32, %eax
popl %ebp
ret
.Ltmp0:
.size main, .Ltmp0-main
.section .note.GNU-stack,"",@progbits
$ gcc -O2 -S ll.c -o -
.file "ll.c"
.text
.p2align 4,,15
.globl main
.type main, @function
main:
leal 4(%esp), %ecx
andl $-16, %esp
pushl -4(%ecx)
movl $32, %eax
pushl %ebp
movl %esp, %ebp
pushl %ecx
popl %ecx
popl %ebp
leal -4(%ecx), %esp
ret
.size main, .-main
.ident "GCC: (GNU) 4.3.2 20081105 (Red Hat 4.3.2-7)"
.section .note.GNU-stack,"",@progbits
Pro ty co nemaji radi assembler - nikde se nevola funkce strlen, ale rovnou se vrati konstanta 32 (delka retezce) v instrukcimovl $32, %eax
Tiskni
Sdílej:
ISSN 1214-1267, (c) 1999-2007 Stickfish s.r.o.