Cloudbook: C

  1. Home
  2. Variables
  3. Pointers
  4. § 3 exercise →
Pointers

Raw access to the underlying memory of any variable is accomplished by getting a pointer to the variable and casting to char * (pronounced char-star). In computer systems, data packets are sent between softwares, which are formatted according to the standard, but are delivered simply as an sequence of bytes. Just as a book has chapters and words, but is ultimately just a sequence of letters, numbers, and punctuation.

Here is a way of taking apart an integer into its individual bytes:

        int i = 0x0d0c0b0a ;
        char * cp ;
        cp = (char *) &i ;
        assert( *cp==0x0a ) ;
        assert( *(cp+1)==0x0b ) ;
        assert( *(cp+2)==0x0c ) ;
        assert( *(cp+3)==0x0d ) ;
        assert( "little endian architecture") ;
        
All assertions are true.

The following is a simplified but instructive example. A filesystem directory in unix is a sequence of file names, each name proceeded by a jump value of the number of bytes to skip to find the next filename. If the jump value is zero there are no more names. The names themselves can be standard null terminated unix strings.

The directory is stored on disk and brought in as a buffer, the simplest description being just a bunch of bytes. Using pointer casting the structure of the data structure can be layered upon the byte buffer:

        char * s  /* = string to match */ ;
        char * cp /* = start of the buffer */ ;
        int n ; 
        
        while (n=*(short *)cp) {
        	if ( !strcmp(s,cp+sizeof(short)) ) break ;
        	cp += n ;
        }
        

It is a strength of C that a location can be simultaneously of several types. Arrays or arrays, and structures of structures provide natural examples. As an "unnatural example", an integer location can be both signed and unsigned:

        int i ;
        unsigned int * uip ;
        int * sip ;
        sip = &i ;
        uip = (unsigned int *) sip ;
        *sip = -1 ;
        assert( *sip<0 ) ;
        assert( *uip<0 ) ;
        
Only the second assertion fails.