为什么数据不会存储在此结构中的任何原因?

Any reason for why data won't be stored in this struct?

我正在将数据存储在结构中,想知道为什么数据没有正确存储在结构中。我已经检查 sscanf 是否正常工作,方法是将其扫描到变量中并打印出来。但是一旦我尝试将它存储在这个结构中,它就不起作用了。

所以我打印了结构,它显示 LocationdirectionnameNULL,因为这是它们的默认值,长度为 0。

Ship *newShip = (Ship*)malloc(sizeof(Ship));
sscanf(line, "%s %s %d %[^\n]", newShip->location, newShip->direction,
       &newShip->length, newShip->name);    
printf("\nShip %d: \n\tLocation: %s \n\tDirection: %s \n\tLength: %d \n\tName: %s\n",
       shipNum, newShip->location, newShip->direction, newShip->length, newShip->name);
shipNum++;

编辑使用的结构如下:

typedef struct {
    char *location;                          
    char *direction;                        
    int length;                             
    char *name;                             
} Ship;

编辑:正在格式化的字符串示例。

"D4 E 3 NullByte Sub"

Ship num 只是我用来跟踪我正在打印的船号的计数。

任何帮助将不胜感激。

您在结构中的指针未指向有效的内存位置,这会导致未定义的行为。

为结构成员分配内存location,direction,name.

例如:

Ship* newShip = malloc(sizeof(Ship));
newShip->location=malloc(size);
newShip->direction=malloc(size);
newShip->name=malloc(size);

size表示每个struct成员的内存大小。

您的结构包含字符串指针,而不是数组。当你用 malloc() 分配它时,你必须将这些指针初始化为一些分配内存,供 sscanf() 存储到。正如发布的那样,代码具有未定义的行为。此外,您应该检查分配失败并验证 sscanf() 返回的转换次数以检测无效输入。

如果你的 C 库支持通用扩展,m 分配修饰符,你可以这样写:

typedef struct {
    char *location;
    char *direction;
    int length;
    char *name;
} Ship;

Ship *create_ship(const char *line) {
    Ship *newShip = calloc(sizeof(Ship), 1);
    if (newShip) {
        if (sscanf(line, "%ms %ms %d %m[^\n]", &newShip->location,
                   &newShip->direction, &newShip->length, &newShip->name) == 4)) {
            printf("\nShip %d:\n\tLocation: %s\n\tDirection: %s\n"
                   "\tLength: %d\n\tName: %s\n", shipNum, newShip->location, 
                   newShip->direction, newShip->length, newShip->name);
        } else {
            /* format error */
            free(newShip->location);
            free(newShip->direction);
            free(newShip);
            newShip = NULL;
        }
    }
    return newShip;
}

对于更简单和更便携的方法,您可以将 Ship 中的字符串字段定义为 char 的数组并使用:

typedef struct {
    char location[20];
    char direction[4];
    int length;
    char name[50];
} Ship;

Ship *create_ship(const char *line) {
    Ship *newShip = calloc(sizeof(Ship), 1);
    if (newShip) {
        if (sscanf(line, "%19s %3s %d %49[^\n]", newShip->location,
                   newShip->direction, &newShip->length, newShip->name) == 4)) {
            printf("\nShip %d:\n\tLocation: %s\n\tDirection: %s\n"
                   "\tLength: %d\n\tName: %s\n", shipNum, newShip->location, 
                   newShip->direction, newShip->length, newShip->name);
        } else {
            /* format error */
            free(newShip);
            newShip = NULL;
        }
    }
    return newShip;
}