获取动态数组大小 [英] obtain dynamic array size

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

问题描述



我在理解以下问题.不过不应该是大事.

如果我有

Hi,

I have issue understanding following. Shouldn''t be a big thing though.

If I have

char buff1[100];
int test1 = sizeof buff1;



然后test1包含100(这是我想要的).

如果我有以下代码:



Then test1 contains 100 (which is what I want).

If I have following code:

char *buff2 = new char[100];
int test2 = sizeof buff2;



然后test2包含4.为什么前一种情况行之有效,而后一种情况不行?我想获得整个(动态)数组的长度. 编辑:好吧,实际上我想慢慢地我开始理解为什么上面的代码返回4(因为buff2只是一个指针,并且它返回了指针的大小,但是没有一种获取整数的方法.动态数组的数组长度?)

谢谢.



then test2 contains 4. Why former case works and later doesn''t ??? I want to obtain length of the whole (dynamic) array. Edited: Well actually I think slowly I start to understand why above code returns 4 (because buff2 is simply a pointer and it returns size of the pointer -- but isn''t there a way to obtain whole array length for dynamic arrays?)

thanks.

推荐答案

报价

没有办法获得全部动态数组的数组长度?

isn''t there a way to obtain whole array length for dynamic arrays?


使用动态C数组,否.如果需要此类信息,并且需要动态调整数组大小,则最好使用STL类std::vector.它会跟踪其大小并自行清理.您甚至可以在运行时动态扩展数组.


Using a dynamic C-array, no. If you need that kind of information, and you need the array to be dynamic in size, you better use the STL class std::vector. It keeps track of it''s size and cleans up after itself. You can even dynamically extend the array at runtime.

std::vector<char> buffer; // defines buffer with initial size 0
const char* hello = "Hello";
buffer.reserve(strlen(hello)); // tells buffer to make room for at least 5 chars
for (std::size_t i = 0; i < strlen(hello); ++i) {
   buffer[i] = hello[i];
}
std::size_t buf_size = buffer.size(); // this value will be 5
buffer.push_back('!'); // dynamically resizes buffer and appends '!'
buf_size = buffer.size(); // size is now 6


在此代码段的末尾,缓冲区包含"Hello!". (但请注意,没有结尾的0字符)

在旁注中,如果您的意图只是存储字符串,请改用std::string.它具有与std::vector相同的功能,但还定义了其他字符串操作.


At the end of this code segment, buffer contains "Hello!" (but note there is no trailing 0 character)

On a sidenote, if your intention is just storing strings, use std::string instead. It has the same functionality as std::vector, but also defines additional string operations.


是的,它与pallani相同.无法获得动态分配的数组大小.获取大小有一个简单的逻辑.
1.保留一个变量以对其进行跟踪.
Yes agree with pallani. Can''t get dynamicaly allocated array size. There is a simple logic to get size.
1. Keep a variable to track of it.


//但是没有办法获取动态数组的整个数组长度吗?

是的,数组可以包装成一个类
正在缓存分配的(和使用的)大小:)
// but isn''t there a way to obtain whole array length for dynamic arrays?

Yes, an array could be wrapped into a class
that is caching the allocated (and used) size(s) :)


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

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