Quick summary: In our activity, we were supposed to declare 3 variables (x, y, and z) and 4 pointer variables (p1, p2, p3, and p4). Two of those pointer variables (p3 and p4) should point to the same variable (z).
in this article: https://www.geeksforgeeks.org/pointers-in-c-and-c-set-1-introduction-arithmetic-and-array/
it said:
// C program to demonstrate use of * for pointers in C
#include <stdio.h>
int main()
{
// A normal integer variable
int Var = 10;
// A pointer variable that holds the address of var.
int *ptr = &Var;
// This line prints value at address stored in ptr.
// Value stored is value of variable "var"
printf("Value of Var = %d\n", *ptr);
// The output of this line may be different in different
// runs even on same machine.
printf("Address of Var = %p\n", ptr);
So I did my code:
int main () {
int x = 10;
int *p1= &x;
float y = 12.5;
float *p2 = &y;
Now is for the p3 and p4 pointer variables. I found this thread: Can two pointer variables point to the same memory Address?
which said in the answer: "Yes, two-pointer variables can point to the same object: Pointers are variables whose value is the address of a C object, or the null pointer. multiple pointers can point to the same object:"
char *p, *q;
p = q = "a";
and did that as well:
int main () {
int x = 10;
int *p1= &x;
float y = 12.5;
float *p2 = &y;
char z = 'G';
char *p3, *p4;
p3 = p4 = &z;
My confusion now is when printing p3 and p4:
int main () {
int x = 10;
int *p1= &x;
float y = 12.5;
float *p2 = &y;
char z = 'G';
char *p3, *p4;
p3 = p4 = &z;
printf("%d %.2f %s %s", *p1, *p2, p3, p4);
Why in the line printf("%d %.2f %s %s", *p1, *p2, p3, p4); it only print p3 and p4 only if they don't have the asterisk??
p3andp4are pointers to a single-character literal not a character at the beginning of a nul-terminated string. Use"%c"to output them and derefernce*p3, *p4inprintf("%d %.2f %c %c", *p1, *p2, *p3, *p4);A few links that provide basic discussions of pointers may help. Difference between char pp and (char) p? and Pointer to pointer of structs indexing out of bounds(?)...p3is not a string: it points to a single char, not to a sequence of chars'\0'terminated.putchar(*p3)orputchar(*p4)to output the single characters separately without relying on theprintfformat-string and the"%c"conversion-specifiers. ("%s"expects a pointer to the first character in a nul-terminated string as the argument,"%c"expects an actual characters as the argument) Take a look at the links above -- they are for different problems, but the discussions in the answers provide pointer basics. Good luck with your coding!