June 21st, 2013, 08:13 PM
Pointers and variables
how are pointers and variables different?
I encountered pointers in a chapter of my textbook on functions with multiple outputs.
it said that in the function
signp and wholep are pointers.
double separate (double num, char *signp, int *wholep)
the textbook explained that pointers store addresses of other memory cells.
so if the function call is
1. function takes value and computes output
separate (value, &sn, &whl);
2. output is stored in some cell, say x
3. *signp stores the address of x
4. *signp "points" to the variable sn where the actual data is stored
5. sn goes to the address and stores the data (not the adress)
is this how it works?
also, I notice that in the function calls, there's an ampersand before output variables just like when you store variables from the scanf function.
what is the effect of placing an ampersand before a variable?
June 21st, 2013, 09:06 PM
Yes, you seem to understand correctly, though be careful about that asterix (*).
A variable contains a value, while a pointer contains the location of a value.
You declare a pointer using an asterix; eg,
You also use an asterix to dereference the value that the pointer points to; eg,
char ch = *signp; // assign the char value at signp to the variable ch
*signp = 'm'; // store 'm' to the location pointed to by signp
Every variable is stored somewhere, so it has a location. You can store the location of a variable in a pointer using the address operation, & . That is the ampersand that you are talking about.
When you call a function, all you can pass to it are copies of the arguments, so if you want to change an argument then you have to pass its address so that the function can dereference that address to change those variables. For example, swapping the values in two variables:
You would call that with
void swap(int *a, int *b)
temp = *a;
*a = *b;
*b = temp;
There's nothing magic about it. Every variable has a memory location. All the pointer contains is a memory address. You just need to understand the notation that is being used.
Oh, and also! The name of an array acts the same as a pointer. So for example:
No need for any ampersand, since s is already a pointer.
char *strcpy(char *dest, const char *src);
Last edited by dwise1_aol; June 21st, 2013 at 09:08 PM.
June 21st, 2013, 09:27 PM
so I guess in a function, the pointer acts like a nickname for the argument,
because when you say *a in the swap function, you actually mean x.
I haven't studied arrays yet, but after I do, I'll keep that in mind when I do.