开发者

Memory allocation of global structure

开发者 https://www.devze.com 2023-01-26 12:18 出处:网络
struct ponto *ps = malloc( sizeof(struct ponto) * colunas * linhas ); I had this declared on my main(). However I want it to be globally accessible to all functions. I believe this is made with real
struct ponto *ps = malloc( sizeof(struct ponto) * colunas * linhas );

I had this declared on my main(). However I want it to be globally accessible to all functions. I believe this is made with realloc and declaring this as null or 开发者_如何转开发something on the start of the file. Is this correct?

struct ponto *ps = null;

and then, when I know the size that I need for the struct of arrays:

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

But this doesn't seem to work hehe. Any tips?


Making ps globally visible requires that it is a global variable. You probably also need to do this for the number of columns and lines.

struct ponto *ps;
int colunas, linhas;

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

Now ps is visible to all functions in the source file and through it, they can access the memory it points to.

If you have multiple source files, you'll have to tell them about ps in a header file which declares it

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

realloc performs an entirely different operation, it resizes the buffer ps points to. null does not exist in standard C.


If your problem is really just the scope of the variable, you can do this:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号