數組步長

數組步長

數組步長(stride of an array,也稱increment, pitch或step size)是程式設計時,相鄰數組元素在記憶體中的開始地址的距離,度量單位可以是位元組或者數組元素個數。步長不可小於數組元素的尺寸,但可以大於,表示有填充的位元組。

數組步長如果等於數組元素的尺寸,則數組在記憶體中是連續的。這可稱為單位步長(unit stride)。非單位步長適用於二維數組或多維數組

基本介紹

  • 中文名:數組步長
  • 外文名:stride of an array
  • 學科:程式語言術語
非單位步長的存在理由,填充,平行數組的重疊,非單位步長多維數組例子,

非單位步長的存在理由

填充

許多程式語言允許數據結構對齊。例如:
struct A {    int a;    char b;};struct A myArray[100];
myArray可能具有步長為8,而不是5。這用於最佳化處理時間而不是最佳化最少使用記憶體。

平行數組的重疊

重疊的平行數組:
#include <stdio.h>struct MyRecord {    int value;      char *text;};     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;}
這是一種類型雙關。

非單位步長多維數組例子

非單位步長特別適用於圖像。這允許創建子圖像而不必複製像素。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;    }             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];                  }                }

相關詞條

熱門詞條

聯絡我們