String Input
If you want to read a string into a program, you must first set aside space to store the string and then use an input function to fetch the string.
Creating Space
The first order of business is setting up a place to put the string after it is read. As mentioned earlier, this means you need to allot enough storage to hold whatever strings you expect to read. Don't expect the computer to count the string length as it is read and then allot space for it. The computer won't (unless you write a function to do so). For example, suppose you try something like this:
char *name; scanf("%s", name);
It will probably get by the compiler, but when the name is read, the name will be written over data or code in your program. That's because ...
Get C Primer Plus®, Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.