在 c 中使用 strcpy 通过函数初始化结构
initialising structs via function with strcpy in c
我是 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;
}
您正在按值直接将 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;
}
您正在按值传递结构。 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;
}
我是 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;
}
您正在按值直接将 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;
}
您正在按值传递结构。 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;
}