I have three difference examples mention below. I don’t understand why ex1 has same output for ex2 and differ output for ex3, also why ex2 is not the same as ex3 where I just make a creation in another line!!
ex1
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int x=2;
int *y;
y = &x;
printf("value: %d\n", *y);
printf("address: %d\n", y);
return EXIT_SUCCESS;
}
output
value: 2
address: 2686744
ex2
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int x=2;
int *y = &x;
printf("value: %d\n", *y);
printf("address: %d\n", y);
return EXIT_SUCCESS;
}
output
value: 2
address: 2686744
ex3
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int x=2;
int *y;
*y = &x;
printf("value: %d\n", *y);
printf("address: %d\n", y);
return EXIT_SUCCESS;
}
output
value: 2686744
address: 2130567168
I HAVE BIG MISUNDERSTANDING OF POINTERS WHEN I THINK STAR MUST BECOME WITH (y) NOT (int)
AND I FIGURE OUT THAT STAR WITH (int) NOT (y) (^_^)
NOW EVERYTHING IS CLEAR FOR ME… THANKS FOR ALL YOUR ANSWERS
In example 3, you first declare a pointer:
and then you say that the
intvalue of*yis the address ofx.That’s because with the declaration
int *yyou have:yis of typeint **yis of typeint.So, the right lines of code in example 3 should be: