指针过去式变量
Pointer one-past-variable
据我所知,在 C 中检查指针是否是超出数组末尾的一个元素是完全合法的,如下所示:
char arr[16];
for (char* ptr = arr; ptr != arr + (sizeof arr / sizeof arr[0]); ++ptr) {
// some code
}
我的问题是做这样的事情是否定义明确且合法(请注意,这段代码只是一个例子来说明我的观点。在实际代码中我有处理数组的函数,我想知道我是否可以通过指向本地 char 变量和大小 1 的指针):
char c;
for (char* ptr = &c; ptr != (&c + 1); ++ptr) {
// some code
}
来自 C 标准(6.5.6 加法运算符)
7 For the purposes of these operators, a pointer to an object that is
not an element of an array behaves the same as a pointer to the first
element of an array of length one with the type of the object as its
element type.
所以这个循环
for (char* ptr = &c; ptr != (&c + 1); ++ptr) {
// some code
}
正确。
该规则的主要原因是它允许“类似迭代器”的访问(如果熟悉 C++ iterator
,请想想)。这是有效且定义明确的:
char arr[16];
const char* begin = arr;
const char* end = &arr[16];
for(char* ptr=begin; ptr!=end; ptr++)
但是,我们不允许取消引用arr[16]
,只需指向它即可。
据我所知,在 C 中检查指针是否是超出数组末尾的一个元素是完全合法的,如下所示:
char arr[16];
for (char* ptr = arr; ptr != arr + (sizeof arr / sizeof arr[0]); ++ptr) {
// some code
}
我的问题是做这样的事情是否定义明确且合法(请注意,这段代码只是一个例子来说明我的观点。在实际代码中我有处理数组的函数,我想知道我是否可以通过指向本地 char 变量和大小 1 的指针):
char c;
for (char* ptr = &c; ptr != (&c + 1); ++ptr) {
// some code
}
来自 C 标准(6.5.6 加法运算符)
7 For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.
所以这个循环
for (char* ptr = &c; ptr != (&c + 1); ++ptr) {
// some code
}
正确。
该规则的主要原因是它允许“类似迭代器”的访问(如果熟悉 C++ iterator
,请想想)。这是有效且定义明确的:
char arr[16];
const char* begin = arr;
const char* end = &arr[16];
for(char* ptr=begin; ptr!=end; ptr++)
但是,我们不允许取消引用arr[16]
,只需指向它即可。