I have spent ages trying to figure out what is the problem with the following program:
typedef struct user {
char host[40];
int order;
} user;
typedef struct data {
user userdat;
} data;
int read_user (char *datname, user *userdat) {
...
fscanf (datin, "%s", &userdat->host);
fscanf (datin, "%d", &userdat->order);
//1
printf ("%d\n", userdat->order);
...
}
void init_data (data *dat) {
init_userdat (&dat->userdat);
}
void init_userdat (user *userdat) {
*userdat->host = "127.0.0.1";
userdat->order = 0;
}
int user_print (int i, data *dat) {
//2
printf ("%d\n", dat->userdat.order);
}
int main(int argc, char *argv[]) {
...
data dat;
init_data (&dat);
read_user (datname, &dat->userdat);
user_print (&dat);
}
The program is very simplified to highlight the relevant sections. What happens is that the first print statement (//1) outputs the value correctly, while the second (//2) does not - it outputs something that looks like a possible memory location.
I have tried numerous combinations of accessing the stored variable, but I just can't crack it. Any help would be appreciated.
Edit1: Fixed up a couple of non essential errors in code (not relating to pointers or structs)
Final Edit: Thank you all for your help. The issue that Arun Saha pointed out was indeed in the original code and is now fixed. However, the problem of printing two different strings persisted. Your assurance that the code should otherwise compile and work led me to discover the true culprit - I was not properly initializing another part of the otherwise complex struct and this resulted in overwriting of the user.order variable.
The following line does not do what it appears to do :-)
*userdat->host = "127.0.0.1";
userdata->host is a pointer to the first character in the host[40] array. The above statement would copy only one character from the source string ("127.0.0.1"). To copy the entire string, use the standard library function stncpy()
strncpy( & userdata->host[ 0 ], "127.0.0.1", 40 );
In your main function, when you invoke read_user (datname, &dat->userdat);, I feel there should be a compilation issue. This should be actually read_user (datname, &dat.userdat); as dat is not a pointer, but an object itself.
With this change and Arun's previous recommendation, I have tried your program and it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With