# Thread: Structure Declaration

1. ## Structure Declaration

Hi There,

can some one tell me how to declare a function with a pointer to a structure, i know how to do it with the structure outside of the main function but unclear how to do it with the structure inside.

Code:
```void function();

void main()
{
struct hello{
int goodbye;
int evening;
}
hello.goodbye = 1;
function();

}

void function()
{
printf("%d", hello->goodbye);
}```
basically how do i declare the functions

thanks

2. Code:
```/* First, define the structure outside functions.
** Just the definition, I'm not talking about variables (objects)
** of the structure at this time */
struct hello {
int goodbye;
int evening;
};

/* now the prototype, using pointers to the structure */
void function(struct hello *);

/* The main() function */
int main(void) {
struct hello hello = {1}; /* initialization; all unmentioned members are initialized to 0 */
hello.evening = 42; /* assignment ot a specific member */
function(&hello); /* call the function */
return 0;
}

void function(struct hello *p) {
printf("%d\n", p->goodbye);
}```

3. Well, if you declare struct hello inside main, it will only be visible inside main. Any other function wishing to use that type can't, it doesn't know what such a structure looks like. Thus, as far as I can tell, your question is irrelevant.

If you do want to declare it inside main, you need a semicolon after the struct declaration. Then, declare your variable as usual. Alternatively, you can squeeze the variable definition into the struct definition, but I think it would make your code harder to read.
Code:
```int main(void)
{
struct hello {
int goodbye;
int goodbye;
};
struct hello foo, *bar;  // foo is a variable of type 'struct hello', bar is type 'pointer to struct hello'
// or
struct hello {
int goodbye;
int goodbye;
} foo, *bar;  // same as above, but struct and variables in one statement -- I do not recommend this
...
return 0;
}```
Also, it's int main(void), and return an int at the end, usually 0. Read this: FAQ > main() / void main() / int main() / int main(void) / int main(int argc, char *argv[]) - Cprogramming.com.

Popular pages Recent additions