Struggling to get number of chars in char* [duplicate]

為{幸葍}努か 提交于 2019-12-04 05:22:22

问题


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)?


回答1:


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).




回答2:


The function sizeof() returns the size of a data type in Byte
For example because you define:

char* string = "hello there";

then type of string is char * and size of mostly all pointer is 4 Bytes ( this function returns 4) But type of *string is char and size of every character is 1 Byte ( This function returns 1)
Solution for you :
Alternative 1: Use function strlen() in library 'string.h'

Alternative 2:(from scratch)

int length = 0;
int index = 0;
while ( string[index] != '\0')
{
length++;
index++;
}


来源:https://stackoverflow.com/questions/17009238/struggling-to-get-number-of-chars-in-char

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!