C - 打印功能不打印?

时间:2018-01-31 01:49:21

标签: c string struct

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

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

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

2 个答案:

答案 0 :(得分:0)

你没有回头客。

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

答案 1 :(得分:0)

您没有从函数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; 
}

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

相关问题