[英]can I pass array though pointers without passing the size?
can i pass a multi-dimension array without passing its size using pointers? 我可以传递多维数组而不使用指针传递其大小吗?
#include <iostream>
using namespace std;
void PrintArray( int(*pInt)[3] )
{
// how to iterate here printing pInt content?
int nRow = sizeof(*pInt) / sizeof(int);
cout << nRow << endl; // the result: 3 not 2! i get the nColumns instead!!?
}
int main()
{
int array[2][3] = { {1,2,3},
{4,5,6}};
int(*pArray)[3] = array;
PrintArray(pArray);
return 0;
}
can anyone add the correct definition of PrintArray to print its elements 任何人都可以添加PrintArray的正确定义来打印其元素
Impossible. 不可能。 When the function takes the array, all that is really passed is a pointer to its first element . 当函数采用数组时,真正传递的只是指向其第一个元素的指针 。 That's how arrays work. 这就是数组的工作方式。
is there a way to pass arrays as a pointer and without passing the size? 有没有一种方法可以将数组作为指针而不传递大小?
Arrays are always passed as a pointer to the first element, unless you pass by reference. 数组始终作为指向第一个元素的指针传递,除非您通过引用传递。 If you only have a pointer to the first element, then you need the additional size information somehow, somewhere. 如果只有第一个元素的指针,则需要以某种方式在某个地方获得其他大小信息。 If you pass by reference, then you already have the size information, because it's part of the (complete) type. 如果通过引用传递,那么您已经具有尺寸信息,因为它是(完整)类型的一部分。
You should probably just use std::vector
, anyway. 无论如何,您可能应该只使用std::vector
。 Raw arrays don't behave "normally" in many ways, std::vector
does. 原始数组在很多方面都不会“正常”运行, std::vector
却可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.