gpt4 book ai didi

C++ 将动态指针传递给二维数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:42:10 24 4
gpt4 key购买 nike

这是对先前问题 I previously 的扩展问。我可以使用模板提交动态二维数组并访问元素。现在,假设我有一个指向这样一个数组的指针。我目前正在使用显示的方法 here将我的指针分配给原始二维数组。我最初以为我可以将模板函数的预期输入更改为 (*A)[M][N] 但这是不行的。我是否遗漏了一些关于有人可以解释的指针的概念?

标题.h

#pragma once

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

template<size_t N, size_t M>
void printPtr( int(*A)[M][N]) {
for(int i=0; i < M; i++){
for(int j=0; j<N; j++) {
cout << A[i][j] << " ";
}
cout << endl;
}
}

主要.cpp

#include "header.h"
#include <iostream>
using namespace std;

int main() {

int A[][3] = {
{1,2,3},
{4,5,6},
{7,8,9},
{10,11,12}
};

int (*ptrA)[3] = A;
printPtr(ptrA);
}

最佳答案

如果您一开始不想知道为什么您的代码无法正常工作,请跳至本文末尾

您的代码的问题在于您正在“模拟array decaying通过传递你的指针:

int A[][2] = {
{1,2,3},
{4,5,6},
{7,8,9},
{10,11,12}
};

int (*ptrA)[3] = A;

下面使用 C++11 features 的代码证实了这一点:

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

template <typename T, typename U>
struct decay_equiv :
std::is_same<typename std::decay<T>::type, U>::type
{};

int main() {

int A[][4] = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 },
{ 10, 11, 12 }
};

std::cout << std::boolalpha
<< decay_equiv<decltype(A), int(*)[3]>::value << '\n'; // Prints "true"
}

Example

您应该通过指针或引用将非衰减类型(即包含有关数组维度的所有信息的类型)传递给函数:

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

template<size_t N, size_t M>
void printPtr(int (*A)[M][N] /* Also a reference could work */) {
for(int i=0; i < M; i++){
for(int j=0; j<N; j++) {
cout << (*A)[i][j] << " ";
}
cout << endl;
}
}

int main() {

int A[][6] = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 },
{ 10, 11, 12 }
};

int(*ptrA)[4][7] = &A; // Not a decayed type
printPtr(ptrA);
}

Example

另一种解决方案是首先不使用指向数组的指针,或者在传递对数组的引用时取消引用它:

template<size_t N, size_t M>
void printPtr( int(&A)[M][N]) {
for(int i=0; i < M; i++){
for(int j=0; j<N; j++) {
cout << A[i][j] << " ";
}
cout << endl;
}
}

...
printPtr(A);
printPtr(*ptrA);

Example

关于C++ 将动态指针传递给二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26737828/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com