查找数据大小 [英] Finding Size of data

查看:92
本文介绍了查找数据大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的代码片段:



  char  * str =  nullptr ; 
str = new char [sz]





这里'sz''是运行期间程序要求的。



我的问题是:如何找到str的大小? sizeof()运算符和strlen()函数都不起作用。

解决方案

str的大小将等于sz。 strlen不会工作,因为它会循环,直到找到空字符串终止符''\0''。由于你有一个新的char数组,所有的字符都可能是''\0''。



也许你并没有很好地解释它,sz被传递给一个函数,或者你是想找出分配给sz的值? sz应该是一个大于0的整数值。


我认为使用 char * str = new char [sz]; 已弃用/不合时宜。

如果你进行字符串处理,请尝试使用 std :: string str = ...; 或者如果你处理原始内存尝试使用的std ::矢量<炭> MEM; 。两者都足够智能,以一种体面的方式处理动态内存,即你不必关心new / malloc / calloc / strdup / ...并删除/删除[] / free / ...

请参阅 http://www.cplusplus.com/reference/string/string/ [ ^ ]和http://www.cplusplus.com/reference/vector/vector/ [ ^ ]。



干杯

Andi

Consider the below fragment of code :

char * str = nullptr;
str = new char[sz]         



Here ''sz'' is to be sought by the program during runtime.

My question is : How to find the size of str ? Neither sizeof() operator nor strlen() function work.

解决方案

The size of the str will equal sz. strlen won''t work because it loops until it finds the null string terminator ''\0''. Since you''ve got a new char array, all the characters are probably ''\0''.

Maybe you aren''t explaining it very well, is "sz" being passed into a function, or are you trying to find out what value to assign to sz? sz should be an integer value greater than 0.


I regard using char* str = new char[sz]; as deprecated/anachronistic.
If you do string handling, try using std::string str = ...; or if you work on raw memory try using std::vector<char> mem;. Both are smart enough to handle the dynamic memory in a decent way, i.e. you do not have to care about new/malloc/calloc/strdup/... and delete/delete[]/free/...
See http://www.cplusplus.com/reference/string/string/[^] and http://www.cplusplus.com/reference/vector/vector/[^].

Cheers
Andi


这篇关于查找数据大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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