Having a problem with print strings from structs in C...
typedef struct box{
char *REF_OR_SYS; int num, x, y, w, h, o;
}BOX;
sscanf(str, "%s %d %d %d %d %d %d", &label, &refNum, &x, &y, &w, &h, &o);
BOX detect = {label, refNum, x, y, w, h, o};
printf("\nLABEL IS %s\n", detect.REF_OR_SYS); //Prints out the String correctly
//(Either the word REF or SYS)
return detect;
When this is structure is passed to another structure, everything is displayed right EXCEPT for the string..
void printBox(BOX detect){
printf("Type: %s Ref: %d X: %d Y: %d W: %d H: %d O:%d\n",
detect.REF_OR_SYS, detect.num, detect.x,
detect.y, detect.w, detect.h, detect.o);
}
Am I missing something simple? REF_OR_SYS always prints out as ??_?
Use strdup()
(usually available, if not use malloc()
) to copy the string read into label
by sscanf()
:
detect.REF_OR_SYS = strdup(label);
as when that function returns label
is out of scope and REF_OR_SYS
will be a dangling pointer. Remember to free()
it when no longer required.
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