-1

I want to know the reason behind why I am getting 2 bytes as a size of the character and at the same time 1 byte for the similar character when stored in a place-holder.

    #include <stdio.h>
    void main(void) {
    char a = "$";
    printf("%d\n", sizeof("$")); // Here output is 2 which should be 1
    printf("%d", sizeof(a)); // Here output is 1 which is correct
    }
Ricky Rick
  • 61
  • 1
  • 6
  • 4
    '$' is char whereas "$" is a null terminated string. – unlut Oct 02 '20 at 08:36
  • 2
    `char a = "$";` is wrong, and your compiler should warn you about that. It’s `char a = '$';`. Your compiler should also warn you about `%d`; it should be `%zu` for a size. – Ry- Oct 02 '20 at 08:37
  • 2
    `'$'` has type `int`, ie `sizeof '$' == sizeof (int)`... `"$"` has type `/*read-only*/char[2]`. – pmg Oct 02 '20 at 08:38
  • Can I know the reason why the 'char' type variable is regarded as an 'int' type by the compiler? – Ricky Rick Oct 02 '20 at 08:46
  • 1
    @Ricky_Rick https://stackoverflow.com/questions/2172943/size-of-character-a-in-c-c – unlut Oct 02 '20 at 08:46

1 Answers1

0

it treats "$" as a string, so it's NULL terminated and has a sizeof 2. same would happen if you would do sizeof "a". if you want to get the sizeof the character itself you should do sizeof with '$', that's the symbol for character.

Gilad
  • 305
  • 1
  • 2
  • 8