-3

As far as I know a character constant, viz, 'a', is stored in ASCII format which is internally treated as integer, 97 in case of 'a', that's why sizeof('a') returns 4 on executing but when I use sizeof("a") it returns 2. I have not found any explanation regarding that yet.

My code:

#include <stdio.h>
void main()
{
   int x,y;

   x = sizeof('a');
   y = sizeof("a");

   printf("%d\n",x);

   printf("%d",y);
}

which gives the output:

4
2
Kevin
  • 6,993
  • 1
  • 15
  • 24
GIRISH
  • 101
  • 1
  • 8

1 Answers1

4

'a' is an integer. It has a size of 4 on most computers. It may also be something else, however. 2 is also common on more specialized hardware.

"a" is a string literal. There are two characters: a and \0. They have a size of 1 each, for a total of size 2. However, when you try to assign that, what you get usually is a const char* and that may have a different size.

Blaze
  • 16,736
  • 2
  • 25
  • 44
  • Wow, what a mixup. Thankfully, @PaulOgilvie already edited it for me. – Blaze Oct 05 '18 at 13:53
  • 3
    Were the downvotes because of the `\n` instead of `\0`? This answer is correct. – Kevin Oct 05 '18 at 13:55
  • 1
    @JamesSnook you don't add the size of all elements of an array to get the size of the array? That's what was meant by adding the size of the 2 characters together. – Kevin Oct 05 '18 at 13:59
  • 1
    @JamesSnook, could you tell us how then to explain this size 2? – Paul Ogilvie Oct 05 '18 at 13:59
  • 1
    @Kein my bad, it's been too long since I've used C, just wrote a test to double check and I was wrong. – James Snook Oct 05 '18 at 14:02
  • 1
    `"a"` has type `/*readonly*/char[2]`. In most contexts it is converted to a value of type `/*readonly*/char*` (not `const char*`). – pmg Oct 05 '18 at 14:03
  • 1
    @pmg Odd that I forgot this as I used to do `int len = sizeof(array) / sizeof(arrayType)` quite often. – James Snook Oct 05 '18 at 14:11