Reputation: 1202
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?
Upvotes: 1
Views: 3147
Reputation: 363707
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.
Upvotes: 1
Reputation: 13983
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 );
...
}
Upvotes: 1