Thread: sizeof behaviour!!

  1. #1
    Registered User
    Join Date
    Apr 2006
    Posts
    20

    Post sizeof behaviour!!

    I have this following program:

    Code:
    	        
    char a[] = "VC";
    char *b = "VC";
    printf("\n %d %d",sizeof(a),sizeof(b));

    Which gives me the 'sizeof' output 3 and 4 for a and b respectively
    3 bytes for 'a' is understandable because we have 'V', 'C' and '\0'.

    Whereas, it '4' bytes for b.
    Now, where does the extra one byte come in for b?

    Thanks.

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    sizeof(b) returns the size of a pointer ( 4 on your system ).
    Kurt

  3. #3
    Registered User
    Join Date
    Apr 2006
    Posts
    20
    But both the pointer and the array hold the same content.
    Shouldn't they report the same size?

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Pointers point.

    There is the size of the pointer (usually fixed for any given machine, it looks like 4 on your machine).
    There is the size of what it points to (which could be huge, say megabytes, but in this case is just 3 bytes).

    sizeof() only ever works on the object itself. You can't use sizeof to tell you how much data a pointer is pointing at.
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Malloc,calloc..Sscanf.
    By ozumsafa in forum C Programming
    Replies: 22
    Last Post: 07-26-2007, 01:09 AM
  2. Replies: 14
    Last Post: 06-28-2006, 01:58 AM
  3. finding size of empty char array
    By darsunt in forum C Programming
    Replies: 12
    Last Post: 05-30-2006, 07:23 PM
  4. Model not showing up on screen...
    By Shamino in forum Game Programming
    Replies: 14
    Last Post: 03-09-2006, 08:00 PM
  5. Question about classes and structures.
    By RealityFusion in forum C++ Programming
    Replies: 19
    Last Post: 08-30-2005, 03:54 PM