简体   繁体   English

我可以通过指针传递数组而不传递大小吗?

[英]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的正确定义来打印其元素
  • is there a way to pass arrays as a pointer and without passing the size? 有没有一种方法可以将数组作为指针而不传递大小?
  • thank you for throwing a glance 谢谢你一眼

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.

相关问题 我可以在不传递指针数组的情况下启动协作内核吗? - Can I launch a cooperative kernel without passing an array of pointers? 如何传递和存储包含指向对象的指针的可变大小数组? - How can I pass and store an array of variable size containing pointers to objects? 创建没有指针的可变大小数组 - Create variable size array without pointers 删除没有指定大小的指针数组 - Deleting an array of pointers without a specified size 如何在不使用向量的情况下调整动态指针数组的大小 - How can I resize a dynamic array of pointers without using a vector 如何在不使用循环的情况下快速打印由指针组成的2个字符的二维数组? - How can I quickly printf 2 dimensional array of chars made of pointers to pointers without using a loop? 如何使用指针将numpy数组传递给C ++ / SWIG而不依赖于numpy.i? - How do I pass a numpy array to C++/SWIG using pointers without relying on numpy.i? 在没有明确数组大小的情况下将数组传递给 function - Passing an array to function without explicit array size 如何将可变大小的指针数组作为参数传递给函数 - How to pass a variable size array of pointers as an argument to a function 我可以传递伪装成数组的常量指针吗? - Can I pass constant pointers disguised as arrays?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM