【问题标题】:Memory allocation of global structure全局结构的内存分配
【发布时间】:2010-11-19 15:21:30
【问题描述】:
struct ponto *ps = malloc( sizeof(struct ponto) * colunas * linhas );

我在我的 main() 中声明了这个。但是我希望它对所有功能都可以全局访问。我相信这是用 realloc 制成的,并在文件的开头将其声明为 null 或其他内容。这是正确的吗?

struct ponto *ps = null;

然后,当我知道数组结构所需的大小时:

ps = realloc (ps, sizeof(struct ponto) * colunas * linhas);

但这似乎不起作用嘿嘿。有什么建议吗?

【问题讨论】:

  • 您是如何发现它不起作用的?在 null 上调用 realloc 等效于 malloc

标签: c data-structures memory-management


【解决方案1】:

使ps 全局可见需要它是一个全局变量。您可能还需要对列数和行数执行此操作。

struct ponto *ps;
int colunas, linhas;

int main()
{
    colunas = /* whatever */;
    linhas  = /* whatever */;
    ps = malloc(sizeof(struct ponto) * colunas * linhas);
    /* do other stuff */
}

现在ps 对源文件中的所有函数都是可见的,并且通过它,它们可以访问它指向的内存。

如果你有多个源文件,你必须在声明它的头文件中告诉他们ps

struct ponto { /* whatever */ };  /* define the struct in the header */
extern struct ponto *ps;
extern int colunas, linhas;

realloc 执行完全不同的操作,它调整缓冲区ps 指向的大小。 null 在标准 C 中不存在。

【讨论】:

  • “声明说明符中有两种或多种数据类型”当我声明 struct ponto *ps;这是为什么呢?
  • @Queops,你在struct ponto 的声明后加了分号(;)吗? stackoverflow.com/questions/2098973/…
  • 我的意思是,您是否在 type struct ponto 的声明之后包含了 ;? (不是变量ps。)
  • @Queops,我相信您的原始问题现在已经得到解答。当您需要更多帮助时,请接受答案并发布新问题。
【解决方案2】:

如果你的问题真的只是变量的范围,你可以这样做:

struct ponto *ps = NULL;
...
int main()
{
    ps = malloc( sizeof(struct ponto) * colunas * linhas );
    ...
}

【讨论】:

  • 不需要显式的NULL
  • 另外sizeof *ps 会比sizeof(struct ponto) 更好。
猜你喜欢
  • 1970-01-01
  • 2019-09-10
  • 2015-07-16
  • 2013-11-09
  • 2010-11-20
  • 2022-08-20
  • 2012-03-10
  • 2012-08-12
相关资源
最近更新 更多