Question

I've been making a program that receives from the user a title movie and it's time. the program uses a struct movie containing char title[20] and char time[20] arrays to input the strings, then i define 2 array of pointers to insert the scanned strings from the struct into them(the array of pointer). The scanning and copying is in a while loop that stops when -1 is entered in the movie title. Till now it works fine but when i exit the loop my inserting -1 and print the movie names and times the output turns out to be all -1 for movie titles and just the last timing for movie times. if there is something not clear ask me .please help. this is the code:

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

struct movie {
    char title[20];
    char time[20];
};

char *movieTitle[20],*movieTime[20];
int movieCount=0;

int main() {

    struct movie aMovie={"Hello","Hello"};

    puts("*****Welcome to VOX cinemas*****");
    puts("Please enter the movie title (enter -1 to end):");
    scanf("%s" ,&aMovie.title);

    while(aMovie.title[0]!='-'||aMovie.title[1]!='1') {
        puts("Please enter the movie's time");
        scanf("%s" , &aMovie.time);
        movieTitle[movieCount]=aMovie.title;
        movieTime[movieCount]=aMovie.time;
        printf("movieTitle[%d]=%s\n",movieCount,movieTitle[movieCount]); //a checking print
        printf("movieTime[%d]=%s\n",movieCount,movieTime[movieCount]);  //a checking print
        movieCount++;
        puts("Please enter the movie title (enter -1 to end):");
        scanf("%s", &aMovie.title);
    }

    printf("%s",movieTitle[0]);
    int numberOfMovies=movieCount;
    puts("********************************\n\n\nMovie Title\t\tMovie Time");

    for(movieCount=0;movieCount!=numberOfMovies;movieCount++) {
        printf("%s\t\t\t%s\n", movieTitle[movieCount],movieTime[movieCount]);
    }

    while(1);
}
Was it helpful?

Solution

You need to read up on string operations in C. And pointers.

The following lines of code:

movieTitle[movieCount]=aMovie.title;
movieTime[movieCount]=aMovie.time;

What do you think they do? Copy the strings? No. They copy pointers to strings. Then you go back into your loop and overwrite the strings (and whatever points to them will return the new stuff).

Try this:

movieTitle[movieCount]=strdup(aMovie.title);
movieTime[movieCount]=strdup(aMovie.time);

That allocates new memory and stores a copy of your string in it. You should read up on memory allocation and leaking as well, but for what you pasted, this is probably good enough :D

EDIT:

A few more hints:

Incorrect: scanf("%s", &aMovie.title); Correct: scanf("%s", aMovie.title);

Incorrect: scanf("%s", &aMovie.time); Correct: scanf("%s", aMovie.time);

That's because char s[20] is already a pointer to a pre-allocated 20 byte string. s is type char *. &s will be a pointer to the pointer. It will have type char **.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top