在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
静态数组, 在声明时就分配好内存了, 譬如: var arr1: array[0..255] of Char; arr2: array[0..255] of Integer; begin ShowMessageFmt('数组大小分别是: %d、%d', [SizeOf(arr1), SizeOf(arr2)]); {数组大小分别是: 512、1024} end;
type TArr1 = array[0..255] of Char; TArr2 = array[0..255] of Integer; var arr1: ^TArr1; arr2: ^TArr2; begin New(arr1); New(arr2); arr1^ := '万一的 Delphi 博客'; ShowMessageFmt('%s%s', [arr1^[0], arr1^[1]]); {万一} // ShowMessageFmt('%s%s', [arr1[0], arr1[1]]); {这样也可以} arr2[Low(arr2^)] := Low(Integer); {第一个元素赋最小值} arr2[High(arr2^)] := MaxInt; {第一个元素赋最大值} ShowMessageFmt('%d, %d', [arr2[0], arr2[255]]); {-2147483648, 2147483647} Dispose(arr1); Dispose(arr2); end; //变通一下, 再做一遍这个例子: type TArr1 = array[0..255] of Char; TArr2 = array[0..255] of Integer; PArr1 = ^TArr1; PArr2 = ^TArr2; var arr1: PArr1; arr2: PArr2; begin New(arr1); New(arr2); arr1^ := '万一的 Delphi 博客'; ShowMessageFmt('%s%s', [arr1[0], arr1[1]]); arr2[Low(arr2^)] := Low(Integer); arr2[High(arr2^)] := MaxInt; ShowMessageFmt('%d, %d', [arr2[0], arr2[255]]); {-2147483648, 2147483647} Dispose(arr1); Dispose(arr2); end;
var arr: array of Integer; begin SetLength(arr, 3); arr[0] := Random(100); arr[1] := Random(100); arr[2] := Random(100); ShowMessageFmt('%d,%d,%d', [arr[0],arr[1],arr[2]]); {0,3,86} end;
type TArr = array of Integer; var p: Pointer; begin GetMem(p, 3 * SizeOf(Integer)); {分配能容纳 3 个 Integer 的空间} {这和 3 个元素的 TArr 的大小是一样的, 但使用时需要进行类型转换} TArr(p)[0] := Random(100); TArr(p)[1] := Random(100); TArr(p)[2] := Random(100); ShowMessageFmt('%d,%d,%d', [TArr(p)[0], TArr(p)[1], TArr(p)[2]]); {0,3,86} FreeMem(p); end;
//获取窗口标题(显然不如用前面说过的 StrAlloc 更好) var p: Pointer; begin GetMem(p, 256); GetWindowText(Handle, p, 256); ShowMessage(PChar(p)); {Form1} FreeMem(p); end;
var p: Pointer; begin p := GetMemory(256); GetWindowText(Handle, p, 256); ShowMessage(PChar(p)); {Form1} FreeMemory(p); end;
var p1,p2: Pointer; begin p1 := AllocMem(256); ShowMessage(PChar(p1)); {这里会显示为空} FreeMemory(p1); p2 := GetMemory(256); ShowMessage(PChar(p2)); {这里会显示一些垃圾数据, 内容取决与在分配以前该地址的内容} FreeMemory(p2); end;
type TArr = array[0..MaxListSize] of Char; PArr = ^TArr; var arr: PArr; i: Integer; begin arr := GetMemory(5); for i := 0 to 4 do arr[i] := Chr(65+i); ShowMessage(PChar(arr)); {ABCDE} arr := ReallocMemory(arr, 26); ShowMessage(PChar(arr)); {ABCDE} for i := 0 to 25 do arr[i] := Chr(65+i); ShowMessage(PChar(arr)); {ABCDEFGHIJKLMNOPQRSTUVWXYZ} end;
type TArr = array[0..0] of Char; PArr = ^TArr; var arr: PArr; i: Integer; begin arr := GetMemory(5); for i := 0 to 4 do arr[i] := Chr(65+i); ShowMessage(PChar(arr)); {ABCDE} arr := ReallocMemory(arr, 26); ShowMessage(PChar(arr)); {ABCDE} for i := 0 to 25 do arr[i] := Chr(65+i); ShowMessage(PChar(arr)); {ABCDEFGHIJKLMNOPQRSTUVWXYZ} end;
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论