使用具有全局结构的sizeof [英] Using sizeof with global structure

查看:69
本文介绍了使用具有全局结构的sizeof的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有人的问题......


我正试图确定全球结构的大小。它必须在全局声明,因为它已在几个不同的文件中使用。在编译(BCC32)代码时,我收到错误:

错误E2109 MainTest.c 9:函数main中不允许使用类型


我知道这种情况正在发生,因为结构数组的大小是未定义的[]。但我不能提前定义大小。


代码是从命令行编译的命令:

BCC32测试.c MainTest.c


如果有更好的方法,我愿意接受建议。


这是代码的小版本:


MainTest.c:

展开 | < span class =codeLinkonclick =selectAll(this);>选择 | 换行 | 行号

解决方案

您可以在Test.c中编写一个函数,使用您已有的公式返回数组的大小。


该公式应该在Test.c中工作,因为数组的大小是在那里定义的。


显然你会在Test.h中声明该函数。


PS主要应该宣布


int main()


不是

void main()


C(和C ++)标准指定main返回int,而不是返回int,最好使用编译器扩展,使您的代码不必要地不可移植,最坏的行为导致发生任何事情。


您必须在某个位置定义TextStruct数组的文件(不仅仅是声明)。在同一个文件中,您可以定义一个全局常量:

展开 | 选择 | Wrap | 行号


Question for all...

I''m trying to determine the size of a global structure. It has to be declared globally because it''s used in several different files. When compiling (BCC32) the code I get the error:

Error E2109 MainTest.c 9: Not an allowed type in function main

I know this is happening because the array of structures is of an undefined size []. But I can''t define the size ahead of time.

The code was compiled from the command line with the command:

BCC32 Test.c MainTest.c

If there is a better way to do this I''m open to suggestions.

Here''s a small version of the code:

MainTest.c:

Expand|Select|Wrap|Line Numbers

解决方案

You could write a function in Test.c that returns the size of your array using the formula you already have.

That formula should work in Test.c because the size of the array is defined there.

Obviously you would declare the function in Test.h.


P.S. main should be declared

int main()

not

void main()

The C (and C++) standard specifies that main returns int, not returning int is at best using a compiler extension making your code unnecessarily non-portable and at worst undefined behaviour resulting in anything happening.


You must have a file someplace where the TextStruct array is defined (not merely declared). In that same file you can define a global constant:

Expand|Select|Wrap|Line Numbers


这篇关于使用具有全局结构的sizeof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆