char *s = "Hi";
printf("%s",s);
s here is a pointer, I set the datatype to "%s", the output is "Hi", the string.
int a = 1;
int *p = &a;
printf("%i", p);
p here is also a pointer, I set the datatype to "%i", why the output is not "1", the integer?
In the two cases, if I set the datatypes to "%p", they both will give me the address of the variable. But if I set the datatypes to the datatype of the variables, why they do not both give the content of the variables store?
>Solution :
Explanation
String
A string is an array of char, this is why strings are typed as char* in C.
When a string ends, a special character is used, \0, you do not have to type this character, as C and most other programming languages will add it automatically.
So, when you type char* s = "Hi";, C is storing an array like so: ["H", "i", "\0"] somewhere in your RAM. The value s is now a pointer to the first element of the array ("H"). You can test this by running printf("%c", *s).
When typing printf("%s", s) you are specifying that you want to print a string because you are using "%s", so C will start to print out characters from whatever s is pointing at until it finds a \0.
int
In the case of int, you are storing an int and then you store its address using p. When you execute printf("%i", p), C prints the value of p, a memory address.
If you wanted to print out the int that is pointed at by p, you would need to execute something like printf("%d", *p), this specifies that I want to print out an int because I’m using "%d", and the integer is whatever p is pointing at, so I dereference the pointer p (*p).
Code snippet
Try running this to see if you get it!
#include <stdio.h>
int main ()
{
char *s = "Hi";
printf("Print the address of the string: %i\n", s);
printf("Print the whole string: %s\n", s);
// s is a pointer to 'H'
printf("Print the address of 'H': %i\n", s);
printf("Print 'H': %c\n", *s);
// If s points to 'H', then s+1 points to 'i'
printf("Print the address of 'i': %i\n", s+1);
printf("Print 'i': %c\n", *(s+1));
// Then there should be a \0 after 'i'
printf("Print the address of '\\0': %i\n", s+1);
printf("Print '\\0' (You shouldn't see anything): %c\n", *(s+2));
int i = 1;
int* p = &i;
printf("Print the address of i: %i\n", p);
printf("Print i: %d\n", *p);
return 0;
}
Book
If you are starting to learn C, I recommend you read "On to C", by Patrick Henry Winston.