1

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?

#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;
}
1
  • Given a function that returns an integer, how do you return the integer? int i = 37; return i;? And you call it int j; …; j = intfunc(29); or similar; or int k = 31; int j = intptrfunc(&k);, etc. So, you return a structure the same way: struct student c; …initialization…; return c;. How do you assign the structure in the call: struct student b; …; b = name(&a); (which is also how you pass a pointer to the structure). You don't specify the elements of the structure; you specify the structure variable. Commented Mar 30, 2019 at 6:40

1 Answer 1

1

Your question:

how to return struct variable from a function in c programming?

does not match your code.

In your code you try to return a single struct member (i.e. c.name) but not the whole struct. 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.

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:

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. Like: scanf("%9s", a.name);

Notice that scanf with %s only allows scan of 1 word. As a name can be several words you may want to use fgets instead.

This also applies to the printf, i.e. use %s instead of %c

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.