what is the output of this code

This is a discussion on what is the output of this code within the C Programming forums, part of the General Programming Boards category; Hi all, Code: #include<stdio.h> int main() { char p[]="hello"; printf("sizeof(p)=%d\n",sizeof(p)); printf("sizeof(p+1)=%d\n",sizeof(p+1)); return 0; } the output is 6 and 4 ...

  1. #1
    Registered User
    Join Date
    Jun 2010
    Posts
    22

    Unhappy what is the output of this code

    Hi all,

    Code:
    #include<stdio.h>
    
    int main()
    {
    	char p[]="hello";
    
    	printf("sizeof(p)=%d\n",sizeof(p));
    	printf("sizeof(p+1)=%d\n",sizeof(p+1)); 
    
    	return 0;
    }
    the output is 6 and 4

    Can someone explain why is the output of sizeof(p+1)=4

    Regards and Thanks
    C_Enthusiast

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,553
    p by itself is an array.

    p+1 is an expression. Arrays in expressions become "a pointer to the first element". So what you end up with is sizeof(char*)
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User \007's Avatar
    Join Date
    Dec 2010
    Posts
    179

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Unwanted delay in output
    By NightHawk in forum C Programming
    Replies: 15
    Last Post: 12-07-2010, 08:13 AM
  2. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  3. << !! Posting Code? Read this First !! >>
    By kermi3 in forum Windows Programming
    Replies: 0
    Last Post: 10-14-2002, 01:29 PM
  4. problems with output from code
    By simhap in forum C++ Programming
    Replies: 0
    Last Post: 10-08-2001, 12:43 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21