当我学习C++的时候,我偶然发现了一段代码:
int &get(int *arry, int index) { return arry[index]; }
int main() {
int ia[10];
for (int i = 0; i != 10; ++i)
get(ia, i) = i;
我的问题是,它是如何工作的?
既然arry是一个指针,这怎么可能?
据我所知,堆栈上的多维数组将按行顺序占据连续内存。根据C++标准,使用指向元素的指针对多维数组进行索引是否是未定义的行为?例如:
#include <iostream>
#include <type_traits>
int main() {
int a[5][4]{{1,2,3,4},{},{5,6,7,8}};
constexpr auto sz = sizeof(a) / sizeof(std::remove_all_extents<decltype(a)>::type);
int *p = &a[0][0];
int i = p
我知道在c++中,超出缓冲区边界的访问是未定义的行为。
下面是cp首选项的示例:
int table[4] = {};
bool exists_in_table(int v)
{
// return true in one of the first 4 iterations or UB due to out-of-bounds access
for (int i = 0; i <= 4; i++) {
if (table[i] == v) return true;
}
return false;
}
但是,我在c++标准中找不到段落。
有人
我遇到一个像这样的C++程序
#include<iostream>
using namespace std;
int main() {
int N = 10;
int M = 2;
int a[] = { 2,1,4,3,6,5,8,7,10,9 };
int(*b)[5] = (int(*)[5]) a;
for (int i = 0; i<M; i++) {
for (int j = 0; j<N / M; j++) {
cout << b[i][j] << e