在Delphi中与SetLength一起使用时,动态数组的内存是什么? [英] What's in the memory of a dynamic array when used with SetLength in Delphi?

查看:157
本文介绍了在Delphi中与SetLength一起使用时,动态数组的内存是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动态数组 myArr .当我们在其上使用 SetLength 时,存储在 myArr 中的内存是什么?是"00"吗?还是未定义?

I have a dynamic array myArr. What is stored in the memory in myArr when we use SetLength on it? Is it '00'? Or undefined?

SetLength myArr 分配16个字节的内存.

SetLength allocates 16 bytes of memory for myArr in this case.

myArr : array of byte;

SetLength(myArr, 16);

推荐答案

从Delphi 7帮助中引述,对于长字符串或动态数组变量, SetLength 将重新分配引用的字符串或数组按 S 到给定的长度.保留数组中的字符串或元素,但新分配的空间的内容未定义.一个例外是增加动态数组的长度,在动态数组中,元素是必须初始化的类型(字符串,Variant,Variant数组或包含此类的记录).当 S 是必须初始化的类型的动态数组时,新分配的空间将设置为 0 nil ."

Quoted from the Delphi 7 help, "For a long-string or dynamic-array variable, SetLength reallocates the string or array referenced by S to the given length. Existing characters in the string or elements in the array are preserved, but the content of newly allocated space is undefined. The one exception is when increasing the length of a dynamic array in which the elements are types that must be initialized (strings, Variants, Variant arrays, or records that contain such types). When S is a dynamic array of types that must be initialized, newly allocated space is set to 0 or nil."

根据我的观察,对于静态数组,未初始化的元素包含随机数据.对于动态数组,从Delphi 7开始,AFAIK都未初始化的元素包含其 default nothing 值.但是,您不应该依赖这个事实,因为它是 SetLength 的实现细节.您应该改用官方文档.

From my observation, for static array, uninitialized elements contain random data. For dynamic array, AFAIK since Delphi 7, uninitialized elements contain their default nothing value. However, you shouldn't rely on this fact because it was implementation detail of SetLength. You should follow the official documentation instead.

这篇关于在Delphi中与SetLength一起使用时,动态数组的内存是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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