[英]How to calculate size of an external array?
Does anyone know how to calculate the size of an array from an external file? 有谁知道如何从外部文件计算数组的大小?
Consider: 考虑:
float arr[]={1.4, 2.3, 7.6, 4.8, 3.3};
Main.c
#include <stdio.h> int main() { extern float arr[]; //... }
Then how do I go from there? 那我怎么去那儿? I've tried using
sizeof
and size_t
but there are still errors for both methods. 我尝试过使用
sizeof
和size_t
但两种方法仍然存在错误。
In your main.c file the only information the compiler has is extern float arr[];
在你的main.c文件中,编译器唯一的信息是
extern float arr[];
and this doesn't include a size. 这不包括尺寸。
So either you try to define a function inside Data.c which returns sizeof(arr)
(in this compilation unit the size should be known) or, as you tagged the question c++, you use a std::array
for fixed size or a std::vector
for variable size. 所以你要么尝试在Data.c中定义一个函数,它返回
sizeof(arr)
(在这个编译单元中应该知道大小),或者当你标记问题c ++时,你使用std::array
作为固定大小或者std::vector
用于可变大小。
The problem is that extern float arr[]
is an incomplete type , it only says that "elsewhere, there is an array called arr
of unknown size". 问题是
extern float arr[]
是一个不完整的类型 ,它只是说“在其他地方,有一个名为arr
的未知大小的数组”。 You can only use sizeof
if the size is known, for example on extern float arr[5]
. 如果大小已知,则只能使用
sizeof
,例如在extern float arr[5]
。
However, you should not write programs like this. 但是,你不应该写这样的程序。 Using
extern
on non-constant variables is always an indication of bad program design. 在非常量变量上使用
extern
总是表明程序设计不好。
Instead, you should use private encapsulation and all access to variables should be done through setter/getter functions. 相反,您应该使用私有封装,并且所有对变量的访问都应该通过setter / getter函数来完成。 Similarly, you can create a function
get_size()
which returns the array size. 同样,您可以创建一个返回数组大小的函数
get_size()
。
The short answer is, you can't do what you want. 简短的回答是,你不能做你想做的事。 When you say
当你说
extern float arr[];
the compiler simply doesn't have any way of getting the size of that external array. 编译器根本无法获得该外部数组的大小。
The simple fix is to use a second global variable that carries the size of the array: 简单的解决方法是使用第二个包含数组大小的全局变量:
Data.c Data.c
float arr[]={1.4, 2.3, 7.6, 4.8, 3.3};
int arrsz = sizeof(arr) / sizeof(arr[0]);
Main.c MAIN.C
extern float arr[];
extern int arrsz;
For extra credit, use size_t arrsz
instead of int
. 要获得额外的功劳,请使用
size_t arrsz
而不是int
。
As some other answers have pointed out, though, global variables like this are poor style, especially in "real" programs. 正如其他一些答案所指出的那样,像这样的全局变量风格很差,特别是在“真实”程序中。 For some higher-style, less-simple fixes, see those other answers.
对于一些更高风格,更简单的修复,请参阅其他答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.