Monday, November 12, 2007

Pointers on C

char ch = 'a';
char *cp = &ch;
*cp ;// a
*cp + 1 ;// trash
*cp++ ;// a, return a copy of cp first, than add
*(++cp) ; // trash, add first then return,
(*cp)++ ; // b
[update: 8/13/2013] '++' has higher priority than '*' #

Array and pointer:

int a[4] = {1, 2, 3, 4};
int *ap = a + 2;
ap[0] ; // = 3
ap[-1] ; // = 2

p points to... sizeof (*p) +1 means:add:
p+1 char 1 1

short 2 2

int 4 4

double 8 8

Follow the asterisk rule for parameter passing You can pass an argument back from a routine in C only if you have an asterisk (*) in front of the argument in the assignment statement. Many C programmers have difficulty determining when C allows a value to be passed back to a calling routine. It's easy to remember that, as long as you have an asterisk in front of the parameter when you assign it a value, the value is passed back to the calling routine. Regardless of how many asterisks you stack up in the declaration, you must have at least one in the assignment statement if you want to pass back a value. For example, in the following fragment, the value assigned to parameter isn't passed back to the calling routine because the assignment statement doesn't use an asterisk:

C Example of Parameter Passing That Won't Work
void TryToPassBackAValue( int *parameter )
parameter = SOME_VALUE;
Here, the value assigned to parameter is passed back because parameter has an asterisk in front of it:

C Example of Parameter Passing That Will Work
void TryToPassBackAValue( int *parameter )
*parameter = SOME_VALUE;
--Code Complete (ch.13.2)
Pointer Rules Summary
  • No matter how complex a pointer structure gets, the list of rules remains short.
  • A pointer stores a reference to its pointee. The pointee, in turn, stores something useful.
  • The dereference (*p) operation on a pointer accesses its pointee. A pointer may only be dereferenced after it has been assigned to refer to a pointee. Most pointer bugs involve violating this one rule.
  • Allocating a pointer does not automatically assign it to refer to a pointee. Assigning the pointer to refer to a specific pointee is a separate operation which is easy to forget.
  • Assignment between two pointers makes them refer to the same pointee which introduces sharing.
void BadPointer() {
int* p; // allocate the pointer, but not the pointee
*p = 42; // this dereference is a serious runtime error
a good pointer introduction (link)

another example:
char a[] = {'a', 'b', 'c'};
char b[] = {'d', 'e', 'f'};
char *p = a;
char *q = b;
printf ("p=%c,q=%c\n", *p, *q);//a,d
p = q;
printf ("p=%c,q=%c\n", *p, *q);//d,d
*p = 'k';
printf ("p=%c,q=%c\n", *p, *q);//k,k,b[0]=k
printf ("p=%c,q=%c\n", *p, *q);//k,e
p += 2;
printf ("p=%c,q=%c\n", *p, *q);//f,e

No comments:

Post a Comment