The function definition
Your function definition uses void
, which defines the function as returning nothing, therefore your return
statement is useless (will discuss this later).
Use of structures
Also the definition seems a little broken. You have written:
void initialize_server(struct data host_port) {
Then in your function you write things like data.host
. I'm assuming that you have a struct
definition for data
somewhere and host_port
is the variable of type struct data
.
To create a variable of type struct some-struct-name
you would write struct some-struct-name your-variable-name
. So in your code you could have
struct data {
char host[SIZE];
port_inc[SIZE];
}
This defines the layout of your new composite data type. The type is identified by the name data
. To create variables of this type you would declare them as follows:
struct data my_new_data_struct; // A data structure on the stage of type
struct data *my_new_data_struct; // A pointer to data structure that
// would normally be allocated on the heap
Possible solutions
Use structures passed by value
You could write your function as follows to return the structure, but it will be a little inefficient, because by returning a structure you are likely to be having to utilise the stack to return the data and you are also using the stack to pass in the parameter to the function. This is called pass-by-value.
struct data initialize_server(struct data host_port)
Then replace all data.
bits with host_port.
:
void initialize_server(struct data host_port)
{
printf(" Set IP Address (X.X.X.X): ");
fgets(**host_port**.host, sizeof(**host_port**.host), stdin);
strchomp(**host_port**.host);
printf(" Set Port: ");
fgets(**host_port**.port_inc, sizeof(**host_port**.port_inc), stdin);
strchomp(**host_port**.port_inc);
return **host_port**;
}
Use pointers
What might be better is to pass in a pointer to the data structure as follows:
void initialize_server(struct data *const host_port)
This defines the function initialize_server
as returning nothing, so you won't need to return anyway because not host_port
is a pointer. The function would then become:
void initialize_server(struct data *const host_port)
{
printf(" Set IP Address (X.X.X.X): ");
fgets(data.host, sizeof(host_port->host), stdin);
strchomp(host_port->host);
printf(" Set Port: ");
fgets(host_port->port_inc, sizeof(host_port->port_inc), stdin);
strchomp(host_port->port_inc);
}
But now note that when you call this function you must pass in a pointer! So you might have something like:
void do_something( )
{
struct data my_host_port;
//do stuff
initialize_server( &my_host_port); // NOTE: The ampersand!!
// do stuff
}
Or you might malloc()
your host port as follows.
void do_something( )
{
struct data *my_host_port = malloc(sizeof(struct data));
//do stuff
initialize_server(my_host_port); // NOTE: NO ampersand as my_host_port now already a pointer!!
// do stuff
free(my_host_port); // NOTE: You must free() what you malloc()
}