The Pointer Operator- Definition and Example
The Pointer Operators
There are two special pointer operators: * and &. The & operator is a unary operator that returns the memory address of its operand. (Remember, a unary operator only requires one operand). For example,
m = &count;
places into m the memory address of the variable count. This address is the computer’s internal location of the variable. It has nothing to do with the value of count. You can think of & as returning “the address of.” Therefore, the preceding assignment statement means “m receives the address of count”.
To understand the above assignment better, assume that the variable count uses memory location 2000 to store its value. Also assume that count has a value of 100. Then, after the preceding assignment, m will have the value 2000.
The second pointer operator, * operator, is the complement of &. It is a unary operator that returns the value located at the address that follows. For example, if m contains the memory address of the variable count,
q = *m
places the value of count into q. Thus, q will have the value 100 because 100 is stored at location 2000, which is the memory address that was stored in m. You can think of * as “at address.” In this case, the preceding statement means ” q receives the value at address m.”
Both & and * have a higher precedence than all other arithmetic operators except the unary minus, with which they are equal.
You must make sure that your pointer variables always point to the correct type of data. For example, when you declare a pointer to be of type int, the compiler assumes that any address that it holds points to an integer variable—whether it actually does or not. Because C allows you to assign any address to a pointer variable, the following code fragment compiles with no error messages (or only warnings, depending upon your compiler), but does not produce the desired result:
#include
int main(void)
{
double x = 100.1, y;
int *p;
/* The next statement causes p (which is an
integer pointer) to point to a double. */
p = &x;
/* The next statement does not operate as
expected. */
y = *p;
printf(”%f”, y); /* won’t output 100.1 */
return 0;
}
This will not assign the value of x to y. Because p is declared as an integer pointer, only 2 or 4 bytes of information will be transferred to y, not the 8 bytes that normally make up a double.
Note
In C++, it is illegal to convert one type of pointer into another without the use of an explicit type cast. For this reason, the preceding program will not even compile if you try to compile it as a C++ (rather than as a C) program. However, the type of error described can still occur in C++ in a more roundabout manner.
Popularity: 1% [?]