我正在尝试填充二维数组
list
但是得到do $$
declare pole text[][];
begin
for y in 1..6
loop
for x in 1..4
loop
pole[y][x] = '0';
raise notice 'x: %',x;
raise notice 'y: %',y;
end loop;
end loop;
/*
pole := '{
{0,0,0,0},
{7,0,0,0},
{0,0,0,0},
{0,0,0,0},
{0,0,0,0}
}';
*/
raise notice 'pole : %', pole;
raise notice 'pole one: %', pole[2][1];
end $$
,如果我像pole [6] [4]:='0'那样手动填充数组,那没有问题,但是一旦使用了循环,我就会报错,我不知道为什么变量在1到4到1到6之间,并且手动分配有效。这是基本的编程,我缺少什么吗?
ERROR: array subscript out of range
x86_64-pc-linux-gnu上的PostgreSQL 11.6,由gcc(GCC)4.8.5编译 20150623(Red Hat 4.8.5-39),64位
答案 0 :(得分:3)
像一维数组一样的多维数组cannot grow
可以通过分配元素来扩大存储的数组值 已经存在。先前存在的位置与 新分配的元素将填充为空。例如,如果 数组myarray当前有4个元素,它将有6个元素 在分配给myarray [6]的更新之后; myarray [5]将包含 空值。 当前,仅允许以这种方式进行扩展 一维数组,而不是多维数组。
因此,您必须先初始化数组,然后填充它。
do $$
declare pole text[][];
begin
pole := array_fill(null::text, array[6,4]);
for y in 1..6
loop
for x in 1..4
loop
raise notice 'x: %',x;
raise notice 'y: %',y;
pole[y][x] = '0';
end loop;
end loop;
raise notice 'pole : %', pole;
raise notice 'pole one: %', pole[2][1];
end $$;