Subscribe to the MicroZine Newsletter and collect your free microcontroller Ebooks, download project code and more...

How to use C Pointers for Newbies

This example of C pointers is for people who need a quick practical introduction to using pointers.  It is aimed at usage on a microcontroller but can be used in any compiler since here the compiler is only used in debug mode to step through the code.  Most modern compilers will have a easy-to-use debug mode that will do the same job.

 

Note that this pointers in c example does not explain how to use linked lists only how to get on with c pointers in a practical way.  You can find examples of linked list coding by doing a simple search at a search engine.

The original entry for this code is here
so if you want to make comments or add
more information etc click to go to there now




// Pointers in C language for Newbies by CaptBry.

// actual program and 'article' in Remarks follow - a SIMPLE Demo of Pointers

// C Language demonstration and exploration of Pointers using a Debugger for
// observing the way data is passed and modified in a SIMPLE program.

// A Self-Teaching experiment to learn how Pointers can help
// write subroutines that work for any array passed to them.

// original 14Oct09 MikroC. 4MHz 16F628A, CONFIG = 0x2138, for Debugger ONLY

// Set the Debugger Watch Window to view ALL declared variables:
// if you set the Pointers to display in HEX, they will match the addresses
// shown on the right side of the Watch Window for each array - cool!
// Click BUILD, get "success" then RUN, Debugger, press F8 to step through
// while reading the comments and watching the variables change in Debug.
// Then write your own code to test your new knowledge !
// ENJOY !

//Written on; mikroC, mikroElektronika C compiler
//for Microchip PIC microcontrollers
//Version: 5.0.0.3 all appropriate copyrights to Mike Predko; Genius.
//16F628A @ 4MHz internal OSC, no out put, HS, WDT=OFF
// rewritten 18Dec2010 to clear out some error generating invisible
// characters that creeped into the code. Mostly tabs, and // were guilty.
// END OPENING REMARKS

// DECLARE VARIABLES
char letters[] = "letter";
char message[] = "1234567";
char *pmessage = &message; // doesn't matter; message0 or no dimension
char *pletters = &letters; // next POINTER to an array
char test = 0;             // used mostly to show progress in the Debugger

// SUBROUTINES FOLLOW +++++++++++++++++++++++++++++++++++++++++++
// LOADLETTER() Uses a pointer to put one character into an address passed to it
void loadletter (char *addr, char aletter){ // all LOCAL variables
*addr = aletter; //puts ONE letter into an array
// note these are LOCAL variables whose values are passed by the calling statement.
} // end loadmessage

//LOADARRAY() Uses TWO passed pointers to arrays, and copies #2 into #1
void loadarray (char *addr1, char *addr2){
     while (test != 0){//Using NUL terminated ASCII as recommended by Experts
           test = *addr2++;//shows each character in 'test' under the Debugger
           *addr1++ = test;//copies a single character and THEN increments addr1
           }//wend
}//end loadarray // just keeping track of each function bracket


//MY STRING LENGTH() Takes a pointer to your array and RETURNS its length
char mystrlen (char *addr1){ //pass the array's ADDRESS
char i = 0;                  //use a counter
test = *addr1;               //test becomes the first character of the array
     //Watch test change in the Debugger as a CHAR
     while (test != 0){    //Until you find the NUL (end of array),
           ++i;               //increment the counter
           test = *(addr1+i); //Demonstrates math on the Pointer works fine
           } //wend              //Change the Debugger to show test as DEC
     test = i;             //Shows the counter's value in Debugger
return(i);            //Return the length of the array
}//end mystrlen

void main() {
test = 1; // gives the Debugger a place to show the starting values
// a good programmer would use asm NOP; for less code space ;-)
asm NOP; // insert assembly code No Operation

// message is still "123456" as DEFINEd
*pmessage = 'H'; // message[0] becomes H by using its Pointer
*pmessage++;     // pointer increments from 35 to 36; its just a number
*pmessage = 'i'; //message[1] goes to ASCII i
//the array, message, is now Hi3456NUL Where NUL is zero, a terminator

loadletter(++pmessage, '!'); // now message is Hi!456NUL
//loadarray(++pmessage, &'There'); Sorry, we cant pass multiple chars this way

pmessage = pletters; // simple copy of the number. no reference to what it does.
loadletter(pmessage, 'L');   //puts an L into letters0 using re-callable code
test = message[0];           // H from message, not L from letters0. Data intact!
test = *pmessage;            //IS the L from letters0. Each Pointer stays unique

loadletter(++pletters, 'E'); //loads an E into letter[1]
pmessage = pletters;         //re-assigning works too
loadletter(++pmessage, 'T'); //load T into letters[2]

pmessage = &message;         //set pointer back to the 0 element
pletters = &letters;         //of their original arrays
loadarray ( pmessage , pletters ); //effectively a String Copy routine
// most compiliers have a string copy routine built in, but we can't SEE it work.
pmessage = &message;         //redundant, pmessage is still at the first address
test = mystrlen(message);    //also works if pmessage is passed
// These codes, message = "1234"; and *message = "1234", don't work.

test=0; // reset; to watch it change in Debug

test = mystrlen(pmessage);   //same number comes up, test = 6.
//test is now 6, the length of message, not including the NUL terminator
//note the array in Debug shows TWO zeros,
//yet the string is terminated by the FIRST one. 0 is NULL.
// the defined length of the array just reserves protected space in RAM

while(1 == 1);   //Finished; Loop Forever

} //end main()

//  I hope this little demonstration program helps people learn Pointers and
//  increase the power and versatility of their programming.
// Diferent compiliers use different syntax, so refer to thier unique HELP
// index for examples. The theory is consistent.

// A Pointer is an address of where something is stored in memory. EZ !



if you want to copy above code here it is in plain format

// Pointers in C language for Newbies by CaptBry.                       
                                                                                    
// actual program and 'article' in Remarks follow - a SIMPLE Demo of Pointers       
                                                                                    
// C Language demonstration and exploration of Pointers using a Debugger for        
// observing the way data is passed and modified in a SIMPLE program.               
                                                                                    
// A Self-Teaching experiment to learn how Pointers can help                        
// write subroutines that work for any array passed to them.                        
                                                                                    
// original 14Oct09 MikroC. 4MHz 16F628A, CONFIG = 0x2138, for Debugger ONLY        
                                                                                    
// Set the Debugger Watch Window to view ALL declared variables:                    
// if you set the Pointers to display in HEX, they will match the addresses         
// shown on the right side of the Watch Window for each array - cool!               
// Click BUILD, get "success" then RUN, Debugger, press F8 to step through          
// while reading the comments and watching the variables change in Debug.           
// Then write your own code to test your new knowledge !                            
// ENJOY !                                                                          
                                                                                    
//Written on; mikroC, mikroElektronika C compiler                                   
//for Microchip PIC microcontrollers                                                
//Version: 5.0.0.3 all appropriate copyrights to Mike Predko; Genius.               
//16F628A @ 4MHz internal OSC, no out put, HS, WDT=OFF                              
// rewritten 18Dec2010 to clear out some error generating invisible                 
// characters that creeped into the code. Mostly tabs, and // were guilty.          
// END OPENING REMARKS                                                              
                                                                                    
// DECLARE VARIABLES                                                                
char letters[] = "letter";                                                          
char message[] = "1234567";                                                         
char *pmessage = &message; // doesn't matter; message0 or no dimension              
char *pletters = &letters; // next POINTER to an array                              
char test = 0;             // used mostly to show progress in the Debugger          
                                                                                    
// SUBROUTINES FOLLOW +++++++++++++++++++++++++++++++++++++++++++                   
// LOADLETTER() Uses a pointer to put one character into an address passed to it
void loadletter (char *addr, char aletter){ // all LOCAL variables
*addr = aletter; //puts ONE letter into an array
// note these are LOCAL variables whose values are passed by the calling statement.
} // end loadmessage

//LOADARRAY() Uses TWO passed pointers to arrays, and copies #2 into #1
void loadarray (char *addr1, char *addr2){
     while (test != 0){//Using NUL terminated ASCII as recommended by Experts
           test = *addr2++;//shows each character in 'test' under the Debugger
           *addr1++ = test;//copies a single character and THEN increments addr1
           }//wend
}//end loadarray // just keeping track of each function bracket


//MY STRING LENGTH() Takes a pointer to your array and RETURNS its length
char mystrlen (char *addr1){ //pass the array's ADDRESS
char i = 0;                  //use a counter
test = *addr1;               //test becomes the first character of the array
     //Watch test change in the Debugger as a CHAR
     while (test != 0){    //Until you find the NUL (end of array),
           ++i;               //increment the counter
           test = *(addr1+i); //Demonstrates math on the Pointer works fine
           } //wend              //Change the Debugger to show test as DEC
     test = i;             //Shows the counter's value in Debugger
return(i);            //Return the length of the array
}//end mystrlen

void main() {
test = 1; // gives the Debugger a place to show the starting values
// a good programmer would use asm NOP; for less code space ;-)
asm NOP; // insert assembly code No Operation

// message is still "123456" as DEFINEd
*pmessage = 'H'; // message[0] becomes H by using its Pointer
*pmessage++;     // pointer increments from 35 to 36; its just a number
*pmessage = 'i'; //message[1] goes to ASCII i
//the array, message, is now Hi3456NUL Where NUL is zero, a terminator

loadletter(++pmessage, '!'); // now message is Hi!456NUL
//loadarray(++pmessage, &'There'); Sorry, we cant pass multiple chars this way

pmessage = pletters; // simple copy of the number. no reference to what it does.
loadletter(pmessage, 'L');   //puts an L into letters0 using re-callable code
test = message[0];           // H from message, not L from letters0. Data intact!
test = *pmessage;            //IS the L from letters0. Each Pointer stays unique

loadletter(++pletters, 'E'); //loads an E into letter[1]
pmessage = pletters;         //re-assigning works too
loadletter(++pmessage, 'T'); //load T into letters[2]

pmessage = &message;         //set pointer back to the 0 element
pletters = &letters;         //of their original arrays
loadarray ( pmessage , pletters ); //effectively a String Copy routine
// most compiliers have a string copy routine built in, but we can't SEE it work.
pmessage = &message;         //redundant, pmessage is still at the first address
test = mystrlen(message);    //also works if pmessage is passed
// These codes, message = "1234"; and *message = "1234", don't work.

test=0; // reset; to watch it change in Debug

test = mystrlen(pmessage);   //same number comes up, test = 6.
//test is now 6, the length of message, not including the NUL terminator
//note the array in Debug shows TWO zeros,
//yet the string is terminated by the FIRST one. 0 is NULL.
// the defined length of the array just reserves protected space in RAM

while(1 == 1);   //Finished; Loop Forever

} //end main()

//  I hope this little demonstration program helps people learn Pointers and
//  increase the power and versatility of their programming.
// Diferent compiliers use different syntax, so refer to thier unique HELP
// index for examples. The theory is consistent.

// A Pointer is an address of where something is stored in memory. EZ !


Jump from C Pointers to the home page

New! Comments

Have your say about what you just read! Leave me a comment in the box below.



Privacy Policy | Contact | About Me

Site Map | Terms of Use



Visit our Facebook Page:

   Click Here



Recent Articles

  1. The TCS230 Color Sensing Chip: How it works and how to use it.

    How to use the TCS230 (/TCS3200) Color detector chip and easily add it to any of your projects.

    Read more

  2. Arduino millis

    How to use Arduino millis() for delays but still make the processor do work - Stop using delay()

    Read more

  3. [Arduino Tutorial] : How to use the 74HC595 shift register with shiftOut().

    The Essential Guide to the 74HC595; What it is and how you can easily use one in any of your projects.

    Read more

  4. Pic Programmer Types

    Which pic programmer do you need? This page discusses PIC programmers and gives some essential information on choosing or building your own programmer.

    Read more

  5. Arduino Pulsein: an easy way to measure pulse periods in microseconds.

    learn how to use Arduino pulseIn and pulseInLong to get the most accurate pulse measurement on an Arduino.

    Read more

  6. Multiple MCP23017 Interrupt tutorial for operating multiple interrupts from multiple MCP23017s.

    This MCP23017 Interrupt tutorial shows you how to connect interrupt outputs from several MCP23017s to a single microcontroller interrupt pin.

    Read more

Readers Comments

"I wanted to thank
you so so so much
for all the information
you have provided in
your site it's

SUPERB and FANTASTIC."

- Ranish Pottath

"This site really is
the best and my favorite.
I find here many useful
projects and tips."

- Milan

bursach<at>gmail.com<

"Awesome site,
very, very easy and nice
to navigate!"


- Matt
matt_tr<at>
wolf359.cjb.net


Learn Microcontrollers

"Interested in
Microcontrollers?"

Sign up for The
Free 7 day guide:

FREE GUIDE : CLICK HERE


"I am a newbie to PIC
and I wanted to say
 how great your
site has been for me."


- Dave

de_scott<at>bellsouth.net

"Your site is a great
and perfect work.
congratulations."


- Suresh

integratredinfosys<at>
yahoo.com

"I couldn't find the correct
words to define
yourweb site.

Very useful, uncovered,
honest and clear.

Thanks so much for
your time and works.
Regards."


- Anon

Back to Top