【问题标题】:initialising structs via function with strcpy in c [duplicate]在c中通过带有strcpy的函数初始化结构[重复]
【发布时间】:2019-05-24 22:00:44
【问题描述】:

我是 c 的初学者,我想知道为什么我的函数 feed_struct 不复制我处理的字符串。这个函数 (feed_struct) 应该接受输入数据并将其放入我在全局定义的结构中。有谁知道为什么结构没有任何反应? 提前感谢您的帮助!

void feed_struct(struct student x, char name [20], char lname [20], double a, char adres [50], int b)
{
    strcpy(x.name, name);
    strcpy(x.lastname, lname);
    x.number = a;
    strcpy(x.adres, adres);
    x.course = b;


}

int main (void)
{
    struct student new_student;
    feed_struct(new_student, "Peter", "Panther", 1230, "El-Lobo-Street 32", 72);
    struct_print(new_student);
    return 0;

}  

【问题讨论】:

  • 长话短说:您正在初始化struct student 的副本,原始文件不会更改。传递一个指针。

标签: c struct strcpy


【解决方案1】:

您将new_student 直接按值传递给feed_struct。所以函数的变化在main中是不可见的。

您需要将指向struct student 的指针传递给feed_struct。然后您可以取消引用该指针以更改指向的对象。

// first parameter is a pointer
void feed_struct(struct student *x, char name [20], char lname [20], double a, char adres [50], int b)
{
    strcpy(x->name, name);
    strcpy(x->lastname, lname);
    x->number = a;
    strcpy(x->adres, adres);
    x->course = b;


}

int main (void)
{
    struct student new_student;
    // pass a pointer
    feed_struct(&new_student, "Peter", "Panther", 1230, "El-Lobo-Street 32", 72);
    struct_print(new_student);
    return 0;

}  

【讨论】:

  • 非常感谢,它现在可以工作了!有一件事我仍然没有得到:struct student new_student 不是指针,为什么你可以通过将它的地址传递给 feed_struct 来使用它作为指针?
【解决方案2】:

您正在按值传递结构。 strcpy 调用将字符串复制到结构的本地副本,该副本在函数末尾被丢弃。您应该改为传递一个指向它的指针,以便可以初始化相同的结构:

void feed_struct(struct student* x, /* pointer to struct student */
                 char name [20],
                 char lname [20],
                 double a,
                 char adres [50],
                 int b)
{
    strcpy(x->name, name);
    strcpy(x->lastname, lname);
    x->number = a;
    strcpy(x->adres, adres);
    x->course = b;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    相关资源
    最近更新 更多