-
modifying struct values
Code:
#include <stdio.h>
typedef struct{
int size;
}FileADT;
void setSize(FileADT *file){
file->size=100;
printf("1->%d",file->size);/*prints the file size correctly*/
}
int main(void){
FileADT *a;
a = (FileADT*)malloc(sizeof(FileADT));
setSize(&a);
printf("2->%d",a->size); /*DOESNT WORK.PROGRAM CRASHES*/
};
hi,I got a struct.I want to be able to modify the valueS of the struct.
Inside the set size function,i set the value, and it correctly prints the size in the function.
but back in the main function it doesnt print the file size.
I wonder what mistake i am making
thanks
-
Theres your mistake..
Use:
setSize( a);
setSize (&a) passes in the address of a pointer ie **a
-
> a = (FileADT*)malloc(sizeof(FileADT));
Remove the cast, recompile and make a note of the error message.
Then add
#include <stdlib.h>
and recompile, noting that the error message has gone away.
See the FAQ on why casting malloc in C is a bad idea.
> setSize(&a);
And your compiler didn't complain about this?
Or did you just ignore it and carried on anyway?