Computer Forums

Member Login

Remember Me? Sign Up! | Forgot Password
 
Slogan
 
Closed Thread
Old 01-07-2006, 04:41 AM   #1 (permalink)
 
Newb Techie

Join Date: Dec 2005

Posts: 8

eugensth

Default C problem

Hi,

I dont't understand why happens this thing in C:after compiling and running
this little program:


struct var{
char nume[32];

int*valori;
};

main(){

FILE*p;

struct var test,test2;

test.valori=malloc(sizeof(int));

test.valori[0]=1;

p=fopen("\\date.sta","w");

fwrite(&test,sizeof(struct var),1,p);

fclose(p);

p=fopen("\\date.sta","r");


fread(&test2,sizeof(struct var),1,p);

printf("%d",test2.valori[0]);

fclose(p);

}

the output is this: 1 (as expected),
but if I split this code in 2 separate programs,like this
Program 1:

main(){

FILE*p;

struct var test;

test.valori=malloc(sizeof(int));

test.valori[0]=1;

p=fopen("\\date.sta","w");

fwrite(&test,sizeof(struct var),1,p);

fclose(p);
}

Program 2:

main(){

FILE*p;

struct var test;

test.valori=malloc(sizeof(int));

p=fopen("\\date.sta","r");

fread(&test,sizeof(struct var),1,p);

printf("%d",test.valori[0]);

fclose(p);

}

the output of program 2 is, instead of 1, the unexpected 4239900.
Can somebody explain this to me ?

Thanks
eugensth is offline  
 
Closed Thread

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On