Thread: Reading a string of given size and printing it back

  1. #1
    Registered User
    Join Date
    Apr 2017
    Posts
    3

    Question Reading a string of given size and printing it back

    Hello.

    I'm playing around with C and strings.

    This is piece of code inside main function:
    Code:
    char *format;
    fscanf(fstream, "%2s", format);
    
    
    fprintf(stdout, "%s\n", &format);
    This is what compiler (gcc) spits out when fprintf uses '&' annotation before string variable:
    Code:
    string_test.c: In function ‘main’:
    string_test.c:23:5: error: format ‘%s’ expects argument of type ‘char *’, but argument 3 has type ‘char **’ [-Werror=format=]
         fprintf(stdout, "%s\n", &format);
         ^
    cc1: all warnings being treated as errors
    And this is what compiler spits out when fprintf ommits the '&':
    Code:
    string_test.c: In function ‘main’:
    string_test.c:21:11: error: ‘format’ may be used uninitialized in this function [-Werror=maybe-uninitialized]
         fscanf(fstream, "%2s", format);
               ^
    cc1: all warnings being treated as errors
    What am I supposed to write there then?

  2. #2
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,111
    Code:
    char *format;
    "format" is an uninitialized pointer. You have not allocated any memory to put the data into!

    Try:
    Code:
    char format[80];
    The print statement should be:
    Code:
    fprintf(stdout, "%s\n", format);
    If you are going to show us error messages from a compile, then you should provide a small complete program that demonstrates the error, that we can compile and test ourselves.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Printing string bigger than the maximum size
    By thames in forum C++ Programming
    Replies: 3
    Last Post: 12-14-2012, 05:37 AM
  2. Scale back size of Numbers while maintaining proportion
    By kerrymaid in forum C Programming
    Replies: 5
    Last Post: 10-23-2011, 01:31 PM
  3. Printing the size of a character
    By juice in forum C Programming
    Replies: 18
    Last Post: 09-25-2011, 01:35 AM
  4. printing cd covers the right size?!
    By Leeman_s in forum A Brief History of Cprogramming.com
    Replies: 2
    Last Post: 12-31-2003, 07:03 PM
  5. Printing back arrays
    By Intimd8r in forum C Programming
    Replies: 3
    Last Post: 10-01-2001, 12:50 PM

Tags for this Thread