C 中的全局数组声明?
我需要全局声明一个数组,因为我希望所有方法都能够在 main.c 程序中访问它。但是,如果我在 main.h 中声明它,我将不得不在声明时给它一个大小 - 问题是,我不知道大小,直到调用 InitializeMemory(...) 方法,该方法将用户输入是数组的大小。
I need to declare an array globally, because I want all methods to be able to access it in the main.c program. However, if I declare it in main.h, I will have to give it a size at declaration time - the problem is, I don't know the size until InitializeMemory(...) method is called, which takes user input to be the size of the array.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
像
int *ptr;
一样全局创建它(假设它是整数);然后在你的函数中;
Create it like
int *ptr;
globally (let say it's integer);then in your function;
不要将其设为全局数组,而将其设为全局指针(指向堆分配的数组),并对其进行适当的初始化。
Don't make it a global array, make it a global pointer (to a heap-allocated array), and have it initialized appropriately.
如果您需要分配一个全局数组,其大小仅在运行时知道,那么您只需要一个指针,然后在知道大小后就可以在代码中进行 malloc。
If you need to allocate a global array at with the size only known at runtime, then you want to just a pointer and then you'll malloc in your code once you know the size.