从指针 C++ 获取数组的大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19894686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:14:19  来源:igfitidea点击:

getting size of array from pointer c++

c++arrays

提问by user906357

I am writing a simple function that returns the largest integer in an array. The problem I am having is finding the number of elements in the array.

我正在编写一个返回数组中最大整数的简单函数。我遇到的问题是找到数组中的元素数。

Here is the function header:

这是函数头:

int largest(int *list, int highest_index)

How can I get the number of integers in the array 'list'.

如何获取数组“列表”中的整数数。

I have tried the following methods:

我尝试了以下方法:

int i = sizeof list/sizeof(int); //returns incorrect value
int i = list.size(); // does not compile

Any help will be greatly appreciated!

任何帮助将不胜感激!

回答by kfsone

C++ is based on C and inherits many features from it. In relation to this question, it inherits something called "array/pointer equivalence" which is a rule that allows an array to decay to a pointer, especially when being passed as a function argument. It doesn't mean that an array isa pointer, it just means that it can decay to one.

C++ 基于 C 并继承了它的许多特性。关于这个问题,它继承了一种叫做“数组/指针等价”的东西,这是一个允许数组衰减为指针的规则,特别是当作为函数参数传递时。这并不意味着数组一个指针,它只是意味着它可以衰减为 1。

void func(int* ptr);

int array[5];
int* ptr = array; // valid, equivalent to 'ptr = &array[0]'
func(array); // equivalent to func(&array[0]);

This last part is the most relevant to your question. You are notpassing the array, you are passing the address of the 0th element.

最后一部分与您的问题最相关。您不是在传递数组,而是在传递第 0 个元素的地址。

In order for your function to know how big the incoming array is, you will need to send that information as an argument.

为了让您的函数知道传入数组有多大,您需要将该信息作为参数发送。

static const size_t ArraySize = 5;
int array[ArraySize];
func(array, ArraySize);

Because the pointer contains no size information, you can't use sizeof.

因为指针不包含大小信息,所以不能使用 sizeof。

void func(int* array) {
    std::cout << sizeof(array) << "\n";
}

This will output the size of "int*" - which is 4 or 8 bytes depending on 32 vs 64 bits.

这将输出“int*”的大小 - 根据 32 位和 64 位,它是 4 或 8 个字节。

Instead you need to accept the size parameters

相反,您需要接受大小参数

void func(int* array, size_t arraySize);

static const size_t ArraySize = 5;
int array[ArraySize];
func(array, ArraySize);

Even if you try to pass a fixed-sized array, it turns out this is syntactic sugar:

即使你尝试传递一个固定大小的数组,事实证明这是语法糖:

void func(int array[5]);

http://ideone.com/gaSl6J

http://ideone.com/gaSl6J

Remember how I said that an array is NOT a pointer, just equivalent?

还记得我说过数组不是指针,只是等价的吗?

int array[5];
int* ptr = array;

std::cout << "array size " << sizeof(array) << std::endl;
std::cout << "ptr size " << sizeof(ptr) << str::endl;

array size will be 5 * sizeof(int) = 20 ptr size will be sizeof(int *) which will be either 4 or 8 bytes.

数组大小将是 5 * sizeof(int) = 20 ptr 大小将是 sizeof(int *),它将是 4 或 8 个字节。

sizeof returns the size of the type being supplied, if you supply an object then it deduces the type and returns the size of that

sizeof 返回所提供类型的大小,如果您提供一个对象,那么它会推导出该类型并返回该类型的大小

If you want to know how many elements of an array are in the array, when you have the array and not a pointer, you can write

如果你想知道数组中有多少元素在数组中,当你有数组而不是指针时,你可以写

sizeof(array) / sizeof(array[0])

or sizeof(array) / sizeof(*array)

或 sizeof(array) / sizeof(*array)

回答by john

There's no way to do that. This is one good reason (among many) to use vectors instead of arrays. But if you must use an array then you must pass the size of the array as a parameter to your function

没有办法做到这一点。这是使用向量而不是数组的一个很好的理由(其中之一)。但是如果你必须使用一个数组,那么你必须将数组的大小作为参数传递给你的函数

int largest(int *list, int list_size, int highest_index)

Arrays in C++ are quite poor, the sooner you learn to use vectors the easier you will find things.

C++ 中的数组相当糟糕,你越早学会使用向量,你就越容易找到东西。

回答by Sai Nikhil

The simple answer is you cannot. You need to store it in a variable. The great advantage with C++ is it has STL and you can use vector. size() method gives the size of the vector at that instant.

简单的答案是你不能。您需要将其存储在变量中。C++ 的巨大优势是它具有 STL,并且您可以使用向量。size() 方法给出了该时刻向量的大小。

#include<iostream>
#include<vector>
using namespace std; 
int main () {
    vector<int> v;
    for(int i = 0; i < 10; i++) {
        v.push_back(i);
    }
    cout << v.size() << endl;
    for(int i = 0; i < 10; i++) {
        v.push_back(i);
    }
    cout << v.size() << endl;
    return 0;
}

output:
10
20

输出:
10
20

Not tested. But, should work. ;)

未测试。但是,应该工作。;)

回答by Vlad from Moscow

Pointers do not have information about the number of elements they refer to. If you are speaking about the first argument of the function call then if list is an array you can indeed use the syntax

指针没有关于它们所引用的元素数量的信息。如果你说的是函数调用的第一个参数,那么如果 list 是一个数组,你确实可以使用语法

sizeof( list ) / sizeof( int )

I would like to append that there are three approaches. The first one is to use arrays passed by reference. The second one is to use pointer to the first element and the number of elements. And the third one is to use two pointers - the start pointer and the last pointer as standard algorithms usually are defined. Character arrays have an additional possibility to process them.

我想补充一下,有三种方法。第一个是使用通过引用传递的数组。第二种是使用指向第一个元素和元素个数的指针。第三个是使用两个指针——开始指针和最后一个指针作为标准算法通常被定义。字符数组还有一个处理它们的可能性。

回答by igleyy

You need to remember in a variable array size, there is no possibility to retrieve array size from pointer.

您需要记住在可变数组大小中,不可能从指针中检索数组大小。

const int SIZE = 10;
int list[SIZE];
// or
int* list = new int[SIZE];  // do not forget to delete[]