Thread: code and comments check

  1. #1
    Unregistered
    Guest

    code and comments check

    could someone please check my code and comments (and therefore my thinking) in the following program I think all is correct.

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

    int main(void)
    {
    char msg[20]; /* 0 to 19 = 20 elements the last element should never be accessed */
    /* its reseved for the \0 so in this case 0 to 18 = 19 elements are */
    /* accessable */

    /* read a string from a stream ie stdin, stops reading when it reads n-1 chars */
    fgets(msg, 19, stdin); /* or a newline character whichever comes first */
    /* fgets retains the \n character which is also copied to the array which is */
    /* terminated by an \0 */

    printf("%s",msg);

    return 0;
    }

    /* The array msg has 20 elements 0 to 19 this 19th elements should never be accessed */
    /* because it stores the \0(NULL) now fgets reads n-1 chars ie 19-1=18 chars including */
    /* the \n and the \0 therefor fgets has 18 input chars including the \n */

    /* we could exter as many chars as we wanted these would not be stored in the array */
    /* therefore not going past the array bounds but they would still be in the input buffer*/

    thanks.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Well you were OK upto the fgets

    Code:
    if ( fgets(msg, sizeof(msg), stdin) != NULL ) {
        printf( "%s", msg );
    } else {
        printf( "error\n" );
    }
    > fgets reads n-1 chars
    This count includes the \n, if it is in the first (n-1) characters - you don't have to mess about altering your buffer size

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Code that looks for Comments
    By dgs414 in forum C++ Programming
    Replies: 6
    Last Post: 05-29-2007, 06:36 PM
  2. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  3. can someone double check and maybe improve my code
    By tommy69 in forum C Programming
    Replies: 23
    Last Post: 04-21-2004, 02:04 PM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  5. Code comments
    By salvelinus in forum A Brief History of Cprogramming.com
    Replies: 13
    Last Post: 07-17-2002, 01:27 AM