Thread: sizeof behaviour!!

  1. #1
    Registered User
    Join Date
    Apr 2006

    Post sizeof behaviour!!

    I have this following program:

    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?


  2. #2
    Registered User
    Join Date
    Aug 2005
    sizeof(b) returns the size of a pointer ( 4 on your system ).

  3. #3
    Registered User
    Join Date
    Apr 2006
    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
    The edge of the known universe
    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