Thread: c scanf string pointer?

  1. #1
    Registered User
    Join Date
    Jun 2017
    Posts
    1

    c scanf string pointer?

    How could I make this please:

    Code:
    #include <stdio.h>
    
    int main( void )
    {
        char *name;
    
        scanf( "%s", &name ); // error?
        printf( "Hi %s", name );
    }
    Last edited by qertyer; 06-20-2017 at 10:52 AM.

  2. #2
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,106
    You have not allocated any data space for name.
    Try this:
    Code:
     #include <stdio.h>
     
    int main( void )
    {
        char name[256];
     
        scanf( "%s", &name ); // error?
        printf( "Hi %s", name );
    
        return 0;
    }

  3. #3
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,106
    Actually, the scanf() above should be:
    Code:
    scanf( "%s", name );
    The above code will only input one word, not a full line. Alternatively, you could try:
    Code:
    scanf( "%255s", name );
    Allow for one space for the Nul byte at the end of the array, if 255 or more chars entered.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. scanf and string pointer
    By barramundi9 in forum C Programming
    Replies: 15
    Last Post: 06-01-2011, 02:42 AM
  2. pointer, struct, scanf
    By Alex1357 in forum C Programming
    Replies: 7
    Last Post: 05-06-2011, 09:17 AM
  3. scanf and pointer
    By BlackSlash12 in forum C Programming
    Replies: 4
    Last Post: 04-29-2008, 03:33 PM
  4. char pointer working in scanf but not in cin.
    By sawer in forum C++ Programming
    Replies: 14
    Last Post: 06-15-2006, 02:15 AM
  5. scanf to struct pointer
    By ronenk in forum C Programming
    Replies: 11
    Last Post: 12-20-2004, 10:22 AM

Tags for this Thread