3

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;

これが構造体が別の構造体に渡されると、文字列を除いてすべてが正しく表示されます。

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);

}

私は何か簡単なものが欠けていますか?REF_OR_SYSは常に??_?として出力されます

4

4 に答える 4

6

を使用しstrdup()て(使用しない場合は通常使用可能)、:によってmalloc()読み込まれた文字列をコピーします。labelsscanf()

detect.REF_OR_SYS = strdup(label);

その関数が戻るときlabelはスコープ外でありREF_OR_SYS、ダングリングポインタになります。free()不要になったときに覚えておいてください。

于 2012-06-04T15:05:01.483 に答える
4

ローカル文字配列であると仮定するlabelと、関数ローカルストレージへのポインタを返します。これは、関数が終了すると無効なポインタになります。

あなたはおそらく必要です

char REF_OR_SYS[32];

malloc()または、を使用して(または、文字列strdup()がある場合は)文字列を動的に割り当てます。

于 2012-06-04T15:02:59.750 に答える
1

配列を定義してみてください

typedef struct box{
    char REF_OR_SYS[20]; int num, x, y, w, h, o;
}BOX;
于 2012-06-04T15:04:52.563 に答える
1
typedef struct box{
    char REF_OR_SYS[N]; int num, x, y, w, h, o;
} BOX;

ここで、Nは必要な長さ(定数)であり、

strcpy(detect.REF_OR_SYS, label);
于 2012-06-04T15:07:23.307 に答える