努力获得char *中的字符数 [英] Struggling to get number of chars in char*

查看:199
本文介绍了努力获得char *中的字符数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  char * string =hello there; 

cout<< sizeof(string); // prints 4,这是指针的大小
cout<< sizeof(* string); // prints 1,这是char的大小

如何获取字符数字符串(11)?

解决方案

strlen ,而不是 sizeof 。第一个计算直到终止NUL的字符数,第二个给出类型的大小,在这种情况下,它是一个指针,而不是底层的字符数组。



最后一点,我的意思是:

  char * x =hello there ; 
char y [] =hello there;
std :: cout<< sizeof(x)< ''<< sizeof(y)< '\\\
';

很可能输出如下:



<$在具有32位指针的系统上,p $ p> 4 12



<和8位 char )。在这种情况下, 4 是指针的大小, 12 是数组中的字节数包括最后的NUL)。



无论如何,这是moot,因为 strlen()方法来获取C字符串的长度(是的,即使在C ++中,虽然你可能想考虑使用C ++字符串,因为它们可以节省你很多麻烦)。


char* string = "hello there";

cout << sizeof( string ); // prints 4, which is the size of pointer
cout << sizeof( *string ); // prints 1, which is the size of char

How do I get the number of characters contained in the string (11)?

解决方案

It's strlen you want for that, not sizeof. The first counts the number of characters up to the terminating NUL while the second gives you the size of the type which, in this case, is a pointer rather than the underlying array of characters.

By that last point, I mean:

char *x = "hello there";
char y[] = "hello there";
std::cout << sizeof(x) << ' ' << sizeof(y) << '\n';

will most likely output something like:

4 12

on a system with 32-bit pointers (and 8-bit char). In that case, the 4 is the size of the pointer, the 12 is the number of bytes in the array (including the NUL at the end).

In any case, that's moot, since strlen() is the right way to get the length of a C string (yes, even in C++, though you may want to consider using the C++ strings since they may save you a lot of trouble).

这篇关于努力获得char *中的字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆