Basic pointers in C?

I have three examples of differences mentioned below. I donโ€™t understand why ex1 has the same output for ex2 and differs in output for ex3, also why ex2 is not the same as ex3, where I just do the creation on a different 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; } 

Exit

 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; } 

Exit

 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; } 

Exit

 value: 2686744 address: 2130567168 

I HAVE A BIG CHANGE OF INDICATORS WHEN I THINK THE STAR SHOULD BECOME WITH (y) NOT (int) And I draw that STAR WITH (int) NOT (y) (^_^) NOW EVERYTHING FOR ME ... THANKS FOR ALL OF YOUR ANSWERS

+4
source share
7 answers

In Example 3, you first declare a pointer:

 int *y; 

and then you say that the value int *y is the address x .

This is because with the int *y declaration you have:

  • y is of type int *
  • *y is of type int .

So, the correct lines of code in example 3 should be:

 int *y; y = &x; 
+5
source

Hmm, allows you to enter everything on one line:

 int *y ex1: y = &x ex2: y = &x ex3: (*y) = &x 

Ex3 is different from the other two.

Ex3 assigns the value (& x) to the value indicated by the y pointer.

+2
source

Since the third example says *y = instead of y =

+1
source
 *y 

used to determine the contents of the address pointed to by y

+1
source

int *y; *y = &x; different from int *y = &x; . In the first, you set the contents of the memory location to which y points to the address x . If in the latter, you initialize the y pointer at address x . Therefore, if you remove * from *y = &x , you will see the same result as ex1 and ex2.

+1
source

In ex3, *y = &x; means that you store the address x inside the memory block pointed to by y . This is a problem, since y does not actually indicate anything.

Regardless of printf("address: %d\n", y); fingerprints, there will be no useful information.

+1
source

When declared as *, means "pointer". After that, it is the dereference operator. Consider:

 int x=2; int *y; y=&x; *y = x; 

This is appropriate because addresses are assigned addresses, value values. However, the dereference operator gives you the content, so * y = x does not go beyond. You must treat him as temporary. Therefore, if you pass * y to a function and change it, you will not see any changes when printing * y. You must pass y, that is, follow the link. In short, & y = & x is unstable and not equivalent to y = & x.

See l-value and r-value in C.

+1
source

Source: https://habr.com/ru/post/1401864/


All Articles