Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not printing string from struct in C

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 ??_?

like image 204
SetSlapShot Avatar asked Sep 12 '25 05:09

SetSlapShot


1 Answers

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.

like image 118
hmjd Avatar answered Sep 13 '25 22:09

hmjd