所以我的 C++ 老师在课堂上告诉我们,C++ 中没有确定数组大小的函数,我对此并不满意。我在 stackoverflow 上发现了一个问题,给出了这段代码(sizeof(array)/sizeof(*array)),虽然我不太明白它,但我知道它需要分配给数组的内存总量,并将其除以我假设的其默认内存分配数据类型...(???) 我决定练习编写函数(我在 CS 111 - 基础知识 1)并编写一个函数,该函数返回我传递给它的任何数组中的元素数量。这是我写的:
#include <iostream>
using namespace std;
int length_of_array(int some_list[])
{
// This only returns the integer 1 for some reason
return (sizeof(some_list)/sizeof(*some_list));
}
int main()
{
// Declare and initialize an array with 15 elements
int num_list[] = {2,4,6,8,10,12,14,16,18,20,22,24,26,28,30};
//Outputs what I assume is the total size in bytes of the array
cout << sizeof(num_list) << endl;
//Outputs what I assume to be size of memory set …Run Code Online (Sandbox Code Playgroud)