Thread: Sizeof - Writing past the end of an array

  1. #1
    Registered User
    Join Date
    Jul 2003

    Question Sizeof - Writing past the end of an array

    I'm new to c++ and have a question about a seeming inconsitency I've found in one of my books.

    When taking string input from the keyboard for structures, the examples in my book use the sizeof operator like so:

    cin.getline(, sizeof( - 1);

    The '-1' is used to allow room for the terminating null character.

    Now, I have skipped forward a little in my book so I can add some file I/O to my practice programs.

    However, the I/O examples (using the fstream class) do not subtract 1 from the char array when reading from a file. Why is this? Does this class automatically stop reading 1 byte early, or is this a typo?

  2. #2
    Grammar Police HybridM's Avatar
    Join Date
    Jan 2003
    I'm not 100% sure but I think you're right. The file I/O functions take a number but inside the function they will terminate at number-1.
    Thor's self help tip:
    Maybe a neighbor is tossing leaf clippings on your lawn, looking at your woman, or harboring desires regarding your longboat. You enslave his children, set his house on fire. He shall not bother you again.

    OS: Windows XP
    Compiler: MSVC

  3. #3
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    It says so here:

    Yep, num-1 characters will be read, meaning the getline function will not overrun your buffer:
    #include <iostream>
    using namespace std;
    int main(void)
      char a[5];
      cin.getline(a, 5);
      cout <<a <<endl;
    Input: 123456
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  2. How to load pixels of BMP into an array
    By brconner in forum Windows Programming
    Replies: 10
    Last Post: 06-02-2007, 04:30 AM
  3. Replies: 14
    Last Post: 06-28-2006, 01:58 AM
  4. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM
  5. Character in Array to end for loop.
    By mattz in forum C Programming
    Replies: 6
    Last Post: 12-04-2001, 11:05 AM