0

I want to take string input from user and store it in a structure's pointer variable. The following code works fine in TurboC3 compiler, but fails in MinGW / VSCODE

#include<stdio.h>

typedef struct telephone
{
    char *name;
    int number;
}bullettrain;

int main() {
    bullettrain t[3];
    int i, num;
    for(i=0; i<=2; i++) {
        printf("Enter Your Name: ");
        gets(t[i].name);
        printf("Enter your Number: ");
        scanf("%d", &num);
        t[i].number = num;
        fflush(stdin);
    }
    
    for(i=0; i<=2; i++) {
        printf("Name: %s", t[i].name);
        printf("\nNumber: %d", t[i].number);
        printf("\n-------------------------\n");
    }
    return 0;
}

How to make it work in MinGW / VSCODE?

ITSagar
  • 673
  • 2
  • 10
  • 29
  • You have to allocate memory for `t[i].name`, in any compiler or development tool – Barmak Shemirani Dec 15 '21 at 12:39
  • You don't allocate memory to store the string so your program invokes undefined behavior. You had bad luck not getting the crash when your tried it in one compiler. Furthermore, Turbo C as well as `gets` have been obsolete since ages and `fflush(stdin)` was never valid C. Your current source of learning is teaching you very bad habits, I recommend to replace it. – Lundin Dec 15 '21 at 12:57
  • @Lundin Thanks for the explanation. Can you please suggest a solution and a proper source of learning these concepts? – ITSagar Dec 15 '21 at 13:31
  • Check out the linked duplicate. As for learning, pick some book published this millennium. [Modern C](https://hal.inria.fr/hal-02383654/document) is available for free as pdf but perhaps not the easiest book for beginners. – Lundin Dec 15 '21 at 13:35
  • @Lundin The linked duplicate answers focuses on creating a fix sized memory initially, but I don't want to create a fix sized memory for my string. One answer there suggests that I can use malloc and then use realloc, but that again ends up with the fixed increased size. My plan is to take name from user as input and store it. The length of names may vary for every user, z fixed size location won't work out for me in this context. Any suggestions pleaser? – ITSagar Dec 15 '21 at 13:39
  • C doesn't support infinite input and it doesn't have a string class that does the realloc for you. You need to specify a maximum length supported. Functions like `fgets` can be used to limit input to a certain number of characters. For example, how likely is it that someone has a name longer than 100 characters? – Lundin Dec 15 '21 at 14:01

0 Answers0