How to get the real and total length of char * (char array)?(如何获得char *(char数组)的真实长度和总长度?)
问题描述
对于 char []
,我可以通过以下方式轻松获取其长度:
For a char []
, I can easily get its length by:
char a[] = "aaaaa";
int length = sizeof(a)/sizeof(char); // length=6
但是,我不能这样做来获取 char *
的长度:
However, I cannot do like this to get the length of a char *
by:
char *a = new char[10];
int length = sizeof(a)/sizeof(char);
因为,我知道,这里的 a
是一个指针,因此这里的 length
将始终是 4
(或其他不同的系统).
because, I know, a
here is a pointer, such that length
here will be always be 4
(or something other in different systems).
我的问题是我怎样才能获得 char *
之后的长度?我知道有人可能会质疑我你已经知道它的 10
因为你刚刚创建了它.我想知道这一点,因为获取它的长度的这个步骤可能距离它的创建还有很长的路要走,我不想很长一段时间回来检查这个数字.另外,我也想知道它的真实长度.
My question is that how can I get the length of a char *
afterwards? I know someone may challenge me that you already know its 10
because you just created it. I want to know this because this step of getting its length may come long long way from its creation and I don't want to come long long way back to check this number. Moreover, I also want to know its real length.
更具体
- 我怎样才能得到它真正的
length=5
? - 我怎样才能得到它的总
length=10
?
以下示例:
char *a = new char[10];
strcpy(a, "hello");
推荐答案
你不能.无论如何,不是100%准确.指针没有长度/大小,只有它自己的.它所做的只是指向内存中保存一个字符的特定位置.如果该字符是字符串的一部分,那么您可以使用 strlen
来确定当前指向的字符后面的字符,但这并不意味着您的 array箱子那么大.
基本上:
You can't. Not with 100% accuracy, anyway. The pointer has no length/size but its own. All it does is point to a particular place in memory that holds a char. If that char is part of a string, then you can use strlen
to determine what chars follow the one currently being pointed to, but that doesn't mean the array in your case is that big.
Basically:
指针不是数组,所以它不需要 知道数组的大小.指针可以指向单个值,因此指针可以在没有数组的情况下存在.它甚至不关心它指向的内存位于何处(只读,堆或堆栈......无关紧要).指针除了自身之外没有长度.指针只是...
考虑一下:
A pointer is not an array, so it doesn't need to know what the size of the array is. A pointer can point to a single value, so a pointer can exist without there even being an array. It doesn't even care where the memory it points to is situated (Read only, heap or stack... doesn't matter). A pointer doesn't have a length other than itself. A pointer just is...
Consider this:
char beep = 'a';
void alert_user(const char *msg, char *signal); //for some reason
alert_user("Hear my super-awsome noise!", &beep); //passing pointer to single char!
void alert_user(const char *msg, char *signal)
{
printf("%s%c
", msg, *signal);
}
指针可以是单个字符,也可以是数组的开头、结尾或中间...
将字符视为结构.您有时会在堆上分配一个结构.这也创建了一个没有数组的指针.
A pointer can be a single char, as well as the beginning, end or middle of an array...
Think of chars as structs. You sometimes allocate a single struct on the heap. That, too, creates a pointer without an array.
仅使用指针来确定它指向的数组有多大是不可能的.最接近它的是使用 calloc
并计算您可以通过指针找到的连续 字符的数量.当然,一旦您将内容分配/重新分配给该数组的键,这将不起作用,并且如果数组的 外部 内存恰好保存