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

当这个is结构被传递到另一个结构时,除了字符串,所有内容都会显示在右边。
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_或_sys总是打印为???

最佳答案

使用strdup()(通常可用,如果不使用malloc())通过label将读取的字符串复制到sscanf()中:

detect.REF_OR_SYS = strdup(label);

当函数返回的label超出范围时,REF_OR_SYS将是一个悬空指针。当不再需要时,记得要free()它。

关于c - 不从C中的struct打印字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10883470/

10-13 08:31