All:
Would appreciate some help with c ,in particular C18. I want to pass a variable to a function via an argument. The function would modify the value of the variable, BUT I don't want to just modify the variable inside the function, but the original variable itself, if you know what I mean. I believe I need to be using pointers, but lost on them. To simplify what I am trying to achieve consider the following.
Function foo simply accepts a int variable and changes it to 10 then could do some additional changes to variable j. The original variable is declared and then passed as the variable a, but I want the value of variable a to be changed every time the function foo process a change to variable j.??
*V gives you the value stored at the address contained in V
&V gives you the address of the variable V
I expect the line in bold is what you are after but I included the use of cptr for contrast. Or maybe just confusion.
Code:
char c;
char *cptr = &c; // this means cptr is a pointer to a char at the address used by c, a pointer to c
void doIt(char* x) // parm x is a pointer to a character
{
*x='z'; // set the char pointed to by x to 'z'
}
///////////////////////// Main ////////////////////////
void main()
{
c = 'a';
[B] doIt(&c); // pass c's address[/B]
c = 'b';
doIt(cptr); // pass a pointer with c's address
...
This is ok but see the next post
--------------------------------------------------------------------------------
C18 uses pointers exactly as used in the "HowSTuffWorks" example.
They passed pointers to 2 parameters and I passed 1.
I know this can be confusing but it is not too bad once you get it. Let me try again in its most simple form. Lets look at the call first.
Code:
// In short instead of passing parameter myVar we pass its address &myVar.
void doIt(char* localParm) ; // function prototype
void main()
{
char myVar;
doit(&myVar); // &myVar is a pointer to myVar (its address)
}
//because &myVar is a pointer to a char we write the function with that in mind
void doIt(char* localParm) // char* means pointer to char
{
*localParm = 'z'; // localParm's value is the address of myVar so writing ot *localParm is the same as writting to the myVar
}
Try any of these examples in the simulator and they should work.
Thanks 3v0. Looks like I am on my way with your help. Pointers are one of those things that seem so confusing, but when you actually start to use them they start to make sense. Appreciate your help.