char *name
: name
is a pointer to type char
. Now, when you make it to point to "John"
, the compiler stores the John\0
i.e., 5 chars to some memory and returns you the starting address of that memory. So, when you try to read using %s
(string format specifier), the name
variable returns you the whole string reading till \0
.
char name
: Here name
is just one char having 1 byte of memory. So, you can't store anything more than one char. Also, when you would try to read, you should always read just one char (%c
) because trying to read more than that will take you to the memory region which is not assigned to you and hence, will invoke Undefined Behavior.
int age
: age
is allocated 4 bytes, so you can store an integer to this memory and read as well, printf("%d", age);
int *age
: age
is a pointer to type int and it stores the address of some memory. Unlike strings, you do not read integers using address (loosely saying, just for the sake of avoiding complexity). You have to dereference it. So first, you need to allocate some memory, store any integer into it and return the address of this memory to age
. Or else, if you don't want to allocate memory, you can use compiler's help by assigning a value to age
like this, *age = 27
. In this case, compiler will store 27
to some random memory and will return the address to age
which can be dereferenced using *age
, like printf("%d", *age);