Originally Posted by
patch1024
int a=0;
int x=0;
x=&a;
If &a gives a raw number as it does in the printf command, why can't x take the value of this number? The code works if I use *x=0, but I can't see why it needs that.
Thanks for any help.
hey, pointers giving you hell as well?? yeah well your not the only one around here.
i myself still don't have a firm grasp of it all. but what i think i do know is that pointers are used because when you have several functions etc, you don't want to keep returning some variable(s) becuase this takes up memory. so you use pointers.
quick run down on pointers:
the '&' ampersand. when couple with a variable like '&b'. this gives us the address of b.
the '*' or otherwise known as dereferencing. if we were to write *a. then the '*' gives us access or allows us to change whatever *a is pointing to.
so if you put these two together like so:
a = &b //this assigns the address of b to a.
then later you call a function you use *a to gain access to b. and b could equal to some other number 4. but once *a changes so does b.
say if you want to add two numbers together and write a main with int x, y and the functionname, then you make it print the answer. if you do it the normal way without pointers, sure you can do it that way if you want. but after the user input, you will have to return the variable which is the sum of x, y. then your going to have to create another variable z. the function returns the value of z back into main, then you can either make it equal something else (in this case 'ans') or you can print it like so: printf("%d", mfunction(x,y)); e.g. sorry if you try to run it, i'm not sure why it's running twice.
Code:
int mfunction(int x, int y)
{
int z;
printf("enter number x: ");
scanf(" %d", &x);
printf("enter number y: ");
scanf(" %d", &y);
z = x + y;
return z;
}
main()
{
int x, y, ans;
mfunction(x,y);
ans = mfunction(x,y);
printf("%d", ans);
return 0;
}
ok now we'll try with pointers it'll be about the same but with less variables
Code:
#include <stdio.h>
void mfunction(int *x, int *y)
{
printf("enter number x: ");
scanf(" %d", x);
printf("enter number y: ");
scanf(" %d", y);
}
main()
{
int x, y, ans;
mfunction(&x,&y);
ans = x+y;
printf("%d", ans);
return 0;
}
hope this helps.. sorry if it's not what you want and if i've said any crap please correct me!