[英]how to return struct variable from a function in c programming?
I created a local structure student c inside the function, how to return student c from function to the the student d in the main fuction?我在函数内部创建了一个局部结构student c,如何将student c从函数返回给main函数中的student d?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student
{
char name[10];
}a,b;
struct student name(struct student *ptr)
{
struct student c;
strcpy(c.name,ptr->name);
return c.name; //error
}
int main()
{
printf("enter name");
scanf("%c",&a.name);
b.name=name (&a.name); //error
printf("%c",b.name);
return 0;
}
Your question:你的问题:
how to return struct variable from a function in c programming?如何从c编程中的函数返回结构变量?
does not match your code.与您的代码不匹配。
In your code you try to return a single struct member (ie c.name
) but not the whole struct.在您的代码中,您尝试返回单个结构成员(即c.name
)而不是整个结构。 Since the struct member is a char array (to be used as a string it seems) you get a lot of errors because i C you can't assign string variables (aka char array variables) using the =
operator.由于 struct 成员是一个 char 数组(似乎用作字符串),您会遇到很多错误,因为 i C 您不能使用=
运算符分配字符串变量(又名 char 数组变量)。
If you really wanted to return a struct simply do:如果您真的想返回一个结构,只需执行以下操作:
struct student name(struct student *ptr)
{
struct student c;
strcpy(c.name,ptr->name);
return c; // Just use c instead of c.name;
}
and the call from main
would be:来自main
的调用将是:
b = name(&a);
BTW:顺便提一句:
scanf("%c",&a.name);
is wrong.是错的。 I assume you want to read a word - not just a character - so %s
is the specifier to use.我假设您想阅读一个单词 - 而不仅仅是一个字符 - 所以%s
是要使用的说明符。 Like: scanf("%9s", a.name);
比如: scanf("%9s", a.name);
Notice that scanf
with %s
only allows scan of 1 word.请注意,带有%s
scanf
仅允许扫描 1 个字。 As a name can be several words you may want to use fgets
instead.由于名称可以是多个单词,因此您可能需要使用fgets
来代替。
This also applies to the printf
, ie use %s
instead of %c
这也适用于printf
,即使用%s
而不是%c
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.