【问题标题】:C - print function not printing?C - 打印功能不打印?
【发布时间】:2018-07-10 00:53:33
【问题描述】:

我正在尝试为我的一个结构打印一个字符串值,但它什么也没有打印出来,即使它可以编译。想知道是否有人可以帮助我指出我的功能哪里出了问题。

typedef struct {
    char        firstName[MAX_STR];
    char        lastName[MAX_STR];
    int         numVehicles;
    VehicleType cars[MAX_VEHICLES];
} CustomerType;

void print_customer(CustomerType *c) {
    printf("%s %s, \n", c->firstName, c->lastName);
}

CustomerType create_customer(char* fname, char* lname) {
    CustomerType customer;
    strcpy(customer.firstName, fname);
    strcpy(customer.lastName, lname);
}

int main() {
    CustomerType customers[MAX_CUSTOMERS];
    customers[0] = create_customer("John", "Bob");
    print_customer(&customers[0]);
    return 0;
}

我认为我的问题是我没有在我的打印函数中正确调用字符串值。

【问题讨论】:

  • create_customer 不会返回,这会导致从那里开始出现未定义的行为。打开编译器警告。
  • @deidei 谢谢!就是这样。
  • 在发布有关运行时问题时,就像这个问题一样,发布minimal reproducible example,以便我们可以轻松地重现问题。

标签: c string struct


【解决方案1】:

您没有从函数create_customer 返回客户。尽管如此,您必须动态分配客户。除此之外,我还鼓励您在复制字符串之前检查它们的大小,否则可能会发生溢出。代码如下:

CustomerType create_customer(char* fname, char* lname) {
    /* allocate a new customer */
    CustomerType *c = malloc(sizeof(CustomerType)); /

    /* ensure the string size before copying it */
    int size_str_to_copy = (strlen(fname) >= MAX_STR) ? MAX_STR : strlen(fname);
    /* copy the string with the safe size */
    strncpy(c->firstName, fname, size_str_to_copy);

    /* ensure the string size before copying it */
    size_str_to_copy = (strlen(lname) >= MAX_STR) ? MAX_STR : strlen(lname);
    /* copy the string with the safe size */
    strncpy(c->lastName, lname, size_str_to_copy);

    /* return the allocated customer pointer */
    return customer; 
}

另外,不要忘记释放已创建的客户。

【讨论】:

    【解决方案2】:

    你不是回头客。

    CustomerType create_customer(char* fname, char* lname) {
        CustomerType customer;
        strcpy(customer.firstName, fname);
        strcpy(customer.lastName, lname);
        return customer; 
    }
    

    【讨论】:

    • 您必须分配一个新客户,这是返回堆栈中的客户,将不再有效。
    猜你喜欢
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-29
    • 2013-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多