I am having a hard time understanding the following sets of code. In the lecture, the professor alluded to how char * represents an address to a character. Additionally, he mentioned that in order for someone to go to a particular address, they should use the * sign along with the name of the variable. In the following lines, I have included three different codes.
Code # 1 makes complete sense to me since in order for me to print the first element of the s, I need to "go to it" by typing *s
in the printf function and then since the variable is a character, I have used %c
in the printf function.
Code # 2 also makes sense to me since it gives me an error when I am compiling the code.
The reason is because s
is simply an address, so in order for me to print what is at s, I would need to use *s
in the printf function.
Code # 3 doesn't really make a lot of sense to me. I was expecting an error in compilation since the printf function is using %s
without actually using *s
, however, this code actually prints out "Emma".
I looked at other examples used by the professor and I came up with Code # 4 and Code # 5.
Code # 4 compiled and prints out the integer 50 since we use *p
in the printf function, and using the same logic, code # 5 doesn't compile since I am requesting an int to be printed when I have simply used p
in the printf function, which is simply a hexadecimal address.
What is confusing is that Code # 3 and Code # 5 are pretty much the same as, the only different being that code # 5 deals with integers and address of integers while Code # 3 deals with Chars and addresses of Chars.
I would appreciate it if someone can clarify this for me.
Code # 1
#include <stdio.h>
int main(void)
{
char *s = "Emma";
printf("%c\n", *s);
}
Code # 2
#include <stdio.h>
int main(void)
{
char *s = "Emma";
printf("%c\n", s);
}
Code # 3
#include <stdio.h>
int main(void)
{
char *s = "Emma";
printf("%s\n", s);
}
Code # 4
#include <stdio.h>
int main(void)
{
int n = 50;
int *p = &n;
printf("%i\n", *p);
}
Code # 5
#include <stdio.h>
int main(void)
{
int n = 50;
int *p = &n;
printf("%i\n", p);
}