returned constant pointer, sizeof()

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ramsin
    New Member
    • Jul 2011
    • 15

    returned constant pointer, sizeof()

    Why is the size of the returned pointer, r, equal to four? And why, in (cout << "(" << sizeof(e(i))... ), the e(i) value is returned, but the (cout) in the same e(i) does not print "Hello"? Thanks for help...

    Code:
    // obs! --> jpkg-msg
    #include <iostream>
    using namespace std;
    
    double* const e(double * const);
    
    int main() {
    	double i[11];
    	cout << "The number of elements: "\
    		<< sizeof(i)/sizeof(*i) << endl;
    		
    	cout << "(" << sizeof(e(i)) << ", "\
    		<< sizeof(*(e(i))) << ")" << endl;
    	
    	return 0;
    }
    
    double* const e(double * const r) {
    	cout << "Hello!" << endl;
    	return r;
    }
    Thanks...
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    A pointer in a 32-bit operating system is a variable that contains a 32-bit address. A 32-bit address is 4 bytes. Therefore the pointer must be 4 bytes to contain that address.

    Now look at this code: cout << sizeof(*(e(i))) .

    First e(i) returns a const double*.
    Therefore, *e(i) must be a const double.
    Therefore, the size of that const double is to be displayed.

    Notice the compiler can figure all this out without ever calling the function. That's why your "Hello!" never appears. You can even remove the function code itself and your program will still compile an link.

    Comment

    • Ramsin
      New Member
      • Jul 2011
      • 15

      #3
      Obs, just noticed: The function actually returns a const pointer, not a const double. Since that pointer is constant, which should be the reason why is the size of that function equal to four.

      EDIT[0]: Correct me if I'm wrong :)
      EDIT[1]: Size of double is actually 64-bits.

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        You are correct. The size of a double is to be displayed, which is what I posted. When this code runs on Visual Studio.NET 2008, I get 64displayed, which is what you expected.

        However, the OP asked why sizeof(e(i))... ) is 4. That's because e(i) returns a pointer. That's not the same as sizeof(*(e(i))) , which is the sizeof a double because *(e(i)) is a double.

        Comment

        Working...