0

I'm trying to declare a variable (struct typed) in a function, and manipulate it (read/write) from other functions. However, when I try to use that variable in any function that is not where I declared it, it contains only garbage.

This is my code:

    #include <stdio.h>
    #include <stdlib.h>

    typedef struct
      char name[25];
      int roll;
      float marks;  
    }Student;

    void getInfo(Student student);
    void display(Student student);

    int main(int argc, char *argv[]) {
      Student student;
      getInfo(student);
      display(student);
      return 0;
    }

    void getInfo(Student student){
      printf("Enter student's name: \n");
      scanf("%s", &student.name);
      printf("Enter student's roll: \n");
      scanf("%d", &student.roll);
      printf("Enter student's grade: \n");
      scanf("%f", &student.marks);
    }

    void display(Student student){
      printf("NAME: %s\n", student.name);
      printf("ROLL: %d\n", student.roll);
      printf("GRADE: %.2f\n", student.marks);
    }
2
  • 1
    You have not initialised the struct. The copy that is passed to the input function does not change the original, and so garbage is printed. Commented Mar 3, 2019 at 17:21
  • 4
    Whatever book or tutorial you're reading (or class you're taking) it should have told you that function arguments in C are passed by value. That means arguments are copied, and the functions only have a local copy they work on. Modifying a copy will not change the original. Do some research about emulating pass by reference in C. Commented Mar 3, 2019 at 17:21

1 Answer 1

2

You should pass your struct by reference ( & operator )

#include <stdio.h>
#include <stdlib.h>

typedef struct{
    char name[25];
    int roll;
    float marks;    
} Student;

void getInfo(Student *student);
void display(Student *student);

int main(int argc, char *argv[]) {
    Student student;
    getInfo( &student );
    display( &student );
    return 0;
}

void getInfo(Student *student){
    printf("Enter student's name:");
    scanf("%s", student->name);
    printf("Enter student's roll:");
    scanf("%d", &student->roll);
    printf("Enter student's grade:");
    scanf("%f", &student->marks);
}

void display(Student *student){
    printf("NAME: %s\n", student->name);
    printf("ROLL: %d\n", student->roll);
    printf("GRADE: %.2f\n", student->marks);
}

Demo : https://repl.it/repls/LowNonstopWeb

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.