oreoFlavor
oreoFlavor

Reputation: 11

About structure and function in C

#include <stdio.h>

struct MovieData {
    char title[50];
    char director[50];
    int year;
    int runningTime;
} movie;

void movieInfo(struct MovieData a) {
    scanf(" %[^\n] %[^\n] %d %d", a.title, a.director, &a.year, &a.runningTime);
}

void moviePrint(struct MovieData a) {
    printf("title: %s\ndirector: %s\nrelease year: %d\nrunning time: %d", a.title, a.director, a.year, a.runningTime);
}

int main(void) {
    movieInfo(movie);
    moviePrint(movie);
    return 0;
}

I think "movie" should work in the function because "movie" is parameter of the function, but it doesn't work.

so I change some parts.

#include <stdio.h>

struct MovieData {
    char title[50];
    char director[50];
    int year;
    int runningTime;
} movie;

void movieInfo() {
    scanf(" %[^\n] %[^\n] %d %d", movie.title, movie.director, &movie.year, &movie.runningTime);
}

void moviePrint() {
    printf("title: %s\ndirector: %s\nrelease year: %d\nrunning time: %d", movie.title, movie.director, movie.year, movie.runningTime);
}

int main(void) {
    movieInfo();
    moviePrint();
    return 0;
}

and this code work.

Why the first code doesn't work?

Upvotes: 1

Views: 106

Answers (3)

onur
onur

Reputation: 47

Because the first one you create "struct MovieData a" which is become local variable and when the function ends, this variable ends too. You should give an adress of your movie object as a parameter of function, so your scanf method change variables of movie object

Upvotes: 2

Hitokiri
Hitokiri

Reputation: 3699

In second option, you use the global variable, then it's updated after void movieInfo() function.

But in first option, you pass by value so struct MovieData a (movie becomes local variable when you call this function in main) is not updated.

movieInfo function should change to:

void movieInfo(struct MovieData *a) {
    scanf(" %[^\n] %[^\n] %d %d", a->title, a->director, &a->year, &a->runningTime);
}

In main function, you use:

movieInfo(&movie);

Using the global function is not recommended. You should use first option with the changing as my answer.

Upvotes: 0

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

In your first method, you pass a whole structure as argument. Because that is By Value, there is no way the function can return the values.

There are two ways you can fix this:

  1. return the structure as the function return;

  2. pass a pointer argument so the function fills in the values in the caller's structure.

The first option would result in:

struct MovieData movieInfo(struct MovieData a) {
    scanf(" %[^\n] %[^\n] %d %d", a.title, a.director, &a.year, &a.runningTime);
    return a;
}

The second option would result in:

void movieInfo(struct MovieData *a) {
    scanf(" %[^\n] %[^\n] %d %d", a->title, a->director, &a->year, &a->runningTime);
}

Upvotes: 0

Related Questions