# 指向数组的指针pointer to array

``````array[20]{'a','b','c',...}
pointer = array[6 through 10];
``````

``````*pointer[0] == array[6];
``````

``````*pointer[5] == array[10];
``````

``````5 == sizeof(*pointer) \ sizeof(type);
``````

## 10 个回复10

### ===============>>#1 票数：12 已采纳

``````int array[20] = {'a','b','c','d','e','f','g','h','i','j','k','l'};
int (*pointer)[10 - 6 + 1] = (int (*)[10 - 6 + 1])&array[6];    /* = array[6 through 10] */

printf("(*pointer)[0] = %c\n", (*pointer)[0]);
printf("(*pointer)[4] = %c\n", (*pointer)[4]);
printf("sizeof *pointer / sizeof **pointer = %lu\n", (unsigned long)(sizeof *pointer / sizeof **pointer));
``````

``````unsigned char buffer[102400];
unsigned char *ptr;

/* ... */
ptr = buffer + 500;
read(fd, ptr, 1024); /* Try and read up to 1024 bytes at position buffer[500] */
``````

### ===============>>#2 票数：6

``````int a[4] = {1,2,3,4};
int *b = &a[2];
cout << b[0] << "-" << b[1] << endl;
``````

### ===============>>#3 票数：4

``````#include <iostream>
using namespace std;

int main()
{
int a[10] = { 0, 4, 5, 7, 4, 3, 1, 6, 2, 9 };

int *p1 = &a[3];
int *p2 = &a[7];

for(int *p = p1; p != p2; ++p)
{
cout << *p << endl;
}

return 0;
}
``````

### ===============>>#4 票数：4

``````char pointer[5];
``````

``````char *pointer = array + 6;
``````

``````char a[10];
char b[10];
b = a;
``````

``````unsigned char bigbuf[1UL << 24]; /* or whatever you want */
unsigned char *ptr = bigbuf;
size_t chunk = BUFSIZ;
FILE *fp = fopen("foo.txt", "rb"); /* no error checking */
size_t total = 0;
if (total + chunk > sizeof bigbuf) {
/* oops, not enough space */
}
}
if (ferror(fp)) {
} else {
/* bigbuf now has data, total has the number of bytes */
}
``````

``````T a[10];
``````

``````pointer[1] == a[0]
pointer[2] == a[1]
...
pointer[11] == a[10]
``````

（或者如果你喜欢冒险，在第一个声明的LHS上用一个更大的正数代替1）。

``````pointer[0] == array[6];
``````

``````*pointer[0] == array[6];
``````

### ===============>>#6 票数：3

``````char *p = array + 6;
``````

``````array[i]
``````

``````*(array + i)
``````

### ===============>>#7 票数：2

`pointer = &array[6]` `pointer[0]`现在将引用与`array[6]`相同的值。 直接提取对数组切片的引用并为其保持`sizeof`语义是不可能的。 您可以使用以下内容模拟它：

``````template <class T>
class Slice {
public:
Slice(T* elements, int begin, int end) : m_elements(elements + begin), m_size(end - begin) {}
T& operator[] (int index) {return m_elements[index];}
int size() const {return m_size;}
private:
T* m_elements;
int m_size;
};

int values[10];
Slice<int> slice(values, 5, 10);
values[5] = 3;
assert(slice[0] == values[5]);
assert(slice.size() == 5);
``````

### ===============>>#8 票数：2

``````int* ptr = new int[10];
int* ptrSub = &ptr[5];
``````

### ===============>>#9 票数：1

``````int  array1[10];
int  array2[3];

// reference 3 elements from array1, starting at element 5 in array1
array2 = array1[5];
``````

3回复

1回复

3回复

2回复

2回复

12回复

3回复

1回复

2回复

1回复