Code:
#include<stdio.h>
main()
{
   int x=5, px = &x;
   float y=5.0, py = &y;
   printf("%d %ld\n",x,(long) px);
   printf("%d %ld\n",x+1,(long) ( px+1));
   
   printf("%f %ld\n",y,(long) py);
   printf("%f %ld\n", y+1, (long) (py+1));
   
}


So, to use pointers you declare it like *ptr, but then use it without the *?

Because in this case it is supposed to display &x and &y in printf, so I got to do that.

But if I write the code like this:

Code:
#include<stdio.h>
main()
{
   int x=5, *px = &x;
   float y=5.0, *py = &y;
   printf("%d %ld\n",x,(long) *px);
   printf("%d %ld\n",x+1,(long) ( *px+1));
   
   printf("%f %ld\n",y,(long) *py);
   printf("%f %ld\n", y+1, (long) (*py+1));
   
}



It displays x and y, respectively.

So, if I write *ptr, it refers to the value of the variable it points to, and if I write ptr, it refers to &variable?

But writing *ptr = x causes an error.

So, maybe writing *ptr= &x causes ptr to have the value of &x and *ptr to have the value of x? Is that it? Am I right?
A pointer's value is an address. The dereference operator (*) returns the value at the address contained in the pointer. You appear to be confused by the use of * as an operator and in types.

Code:
int x = 5;
// Bad: implicit cast from pointer to integer.
int px = &x;
// Not valid because px isn't a pointer:
// *px = 6;

// Equivalent: int *qx = &x;
int *qx;
qx = &x;
*qx *= 2;
// x is now 10

// Will almost certainly crash because the pointer isn't initialized.
// This is also an implicit pointer-to-integer conversion.
int *rx;
*rx = &x;
  
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
Page 1 of 1
» All times are UTC - 5 Hours
 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

 

Advertisement