数组步长
数组步长(stride of an array,也称increment, pitch或step size)是程式设计时,相邻数组元素在内存中的开始地址的距离,度量单位可以是字节或者数组元素个数。步长不可小于数组元素的尺寸,但可以大于,表示有填充的字节。
数组步长如果等于数组元素的尺寸,则数组在内存中是连续的。这可称为单位步长(unit stride)。非单位步长适用于二维数组或多维数组,
非单位步长的存在理由
填充
许多程序语言允许数据结构对齐。例如:
struct A {
int a;
char b;
};
struct A myArray[100];
myArray
可能具有步长为8,而不是5。这用于优化处理时间而不是优化最少使用内存。
平行数组的重叠
重叠的平行数组:
#include <stdio.h>
struct MyRecord {
int value;
char *text;
};
/*
Print the contents of an array of ints with the given stride.
Note that size_t is the correct type, as int can overflow.
*/
void print_some_ints(const int *arr, int length, size_t stride)
{
int i;
printf("Address\t\tValue\n");
for (i=0; i < length; ++i) {
printf("%p\t%d\n", arr, arr[0]);
arr = (int *)((unsigned char *)arr + stride);
}
}
int main(void)
{
int ints[100] = {0};
struct MyRecord records[100] = {0};
print_some_ints(&ints[0], 100, sizeof ints[0]);
print_some_ints(&records[0].value, 100, sizeof records[0]);
return 0;
}
这是一种类型双关。
数组剖面
某些程式设计语言如PL/I允许从数组中选项某些列或行作为数组剖面(array cross-section)。[1]:p.262 例如,对于二维数组:
declare some_array (12,2)fixed;
只考虑第二列的一个导出数组可引用为
some_array(*,2)
非单位步长多维数组例子
非单位步长特别适用于图像。这允许创建子图像而不必复制像素。Java示例:
public class GrayscaleImage {
private final int width, height, widthStride;
/** Pixel data. Pixel in single row are always considered contiguous in this example. */
private final byte[] pixels;
/** Offset of the first pixel within pixels */
private final int offset;
/** Constructor for contiguous data */
public Image(int width, int height, byte[] pixels) {
this.width = width;
this.height = height;
this.pixels = pixels;
this.offset = 0;
this.widthStride = width;
}
/** Subsection constructor */
public Image(int width, int height, byte[] pixels, int offset, int widthStride) {
this.width = width;
this.height = height;
this.pixels = pixels;
this.offset = offset;
this.widthStride = widthStride;
}
/** Returns a subregion of this Image as a new Image. This and the new image share
the pixels, so changes to the returned image will be reflected in this image. */
public Image crop(int x1, int y1, int x2, int y2) {
return new Image(x2 - x1, y2 - y1, pixels, offset + y1*widthStride + x1, widthStride);
}
/** Returns pixel value at specified coordinate */
public byte getPixelAt(int x, int y) {
return pixels[offset + y * widthStride + x];
}
}
参考文献
- ^ Hughes, Joan K. PL/I Structured Programming (second ed.). New York: John Wiley and Sons. 1979. ISBN 0-471-01908-9.