Thread: Why there is discrepancy in sizeof output?

  1. #1
    Registered User
    Join Date
    Jan 2014
    Posts
    76

    Why there is discrepancy in sizeof output?

    Code:
    #include <iostream>     //CODE 1
    using namespace std;
    
    
    int main() {
    	char c[]="Hello";     //C-style string
    	cout<<sizeof(c);
    	return 0;
    }
    Code 1 OUTPUT: 6

    Code:
    #include <iostream>          // Code 2
    using namespace std;
    
    
    int main() {
    	char *c="Hello";         //C-style string
    	cout<<sizeof(c);
    	return 0;
    }
    Code 2 OUTPUT: 8

    Why there is discrepancy between the two?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    One is the size of the array.
    The other is the size of the pointer.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    To add to what Salem said, those two definitions are entirely different. The first takes the string and copies it inside a local array of the same size, while the second just copies the pointer of the static, global string. In the second case, trying to change any character may result in a crash, because the compiler or OS may decide to put that string in read-only memory. If you ever need to use the global string directly, "const char*" is much more appropriate.
    Devoted my life to programming...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Floating point discrepancy
    By juice in forum C Programming
    Replies: 1
    Last Post: 10-29-2011, 11:56 PM
  2. wt is output of sizeof('a');?
    By nkrao123@gmail. in forum C Programming
    Replies: 5
    Last Post: 11-26-2009, 04:44 AM
  3. "sizeof" character strings - output issue
    By bunko in forum C Programming
    Replies: 3
    Last Post: 12-03-2008, 06:10 PM
  4. Discrepancy using rand() and array.
    By omnificient in forum C Programming
    Replies: 6
    Last Post: 05-30-2008, 07:46 PM
  5. Replies: 6
    Last Post: 10-15-2007, 08:05 AM

Tags for this Thread