繁体   English   中英

如何在C语言中将字符串与结构一起使用?

[英]How to use strings with structs in C?

我已经看到了这个问题的答案,但对于像我这样的新手来说, 完全是徒劳的,仍然无法使其正常工作。 我试图声明一个名为“ name”的结构的成员,该成员需要一个字符串值,然后试图弄清楚如何获取该值并打印出来。 我尝试过的每一种方式都会产生错误...

typedef struct {
    float height;
    int weight;
    char name[];
} Person;


void calculateBMI(Person x) {
    //printf will go here here
}


int main(int argc, const char * argv[]) {

    Person Michael;
    Michael.height = 62.0;
    Michael.weight = 168;
    Michael.name[] "Michael";

    Person Steve;
    Steve.height = 50.4;
    Steve.weight = 190;
    Steve.name = "Steven";

    calculateBMI(Michael);
    calculateBMI(Steve);
}

您必须指定char数组的长度,如下所示:

typedef struct {
    float height;
    int weight;
    char name[30];
} Person;

然后,使用strcpy进行填充:

int main(int argc, const char * argv[]) {

    Person Michael;
    Michael.height = 62.0;
    Michael.weight = 168;
    strcpy(Michael.name, "Michael");

    Person Steve;
    Steve.height = 50.4;
    Steve.weight = 190;
    strcpy(Steve.name, "Steven");

    calculateBMI(Michael);
    calculateBMI(Steve);
}

在声明一个新的Person类型的变量时,您要在堆栈中分配空间时,这种解决方案在所有常见情况下都是最干净的。 在大多数复杂的场景中,您不知道char数组的大小,也许您需要使其尽可能小。 在这种情况下,您可以使用malloc解决方案。
请记住,每次使用malloc时,都必须记住在处理完数据后free分配的空间。

您可以将名称成员声明为char *并分配空间以将字符串复制到其中

typedef struct {
    float height;
    int weight;
    char *name;
} Person;


size_t length;
const char *name = "Michael";


length       = strlen(name);
Michael.name = malloc(1 + length);

if (Michael.name != NULL)
    strcpy(Michael.name, name);

然后,当您使用完struct ,别忘了free

free(Michael.name);

或按照HAL9000的建议进行操作,但是此解决方案不适用于更长的字符串。

您可以通过创建一个辅助函数来简化此过程,例如

char *dupstr(const char *src)
{
    char   *dst;
    size_t  length;

    if (src == NULL)
        return NULL;
    length = strlen(src);
    dst    = malloc(1 + length);
    if (dst == NULL)
        return NULL;
    strcpy(dst, src);
    return dst;
}    

接着

typedef struct {
    float height;
    int weight;
    char *name;
} Person;

Michael.name = dupstr("Michael");

但使用完结构后,您还需要free拨打电话。

typedef struct {
    float height;
    int weight;
    char name[];
} Person;

此结构没有声明名称的大小,这意味着创建该结构时,还必须为该名称创建空间。

int main(int argc, const char * argv[])
{
    Person *Michael=malloc(sizeof(Person)+strlen("Michael")+1);
    if(!Michael)return 1;
    Michael->height = 62.0;
    Michael->weight = 168;
    strcpy(Michael->name,"Michael");

    calculateBMI(Michael);
    free(Michael);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM