Become a subscriber (Free)

Join 29,000 other subscribers to receive subscriber sale discounts and other free resources.
:
:
Don't worry -- your e-mail address is totally secure. I promise to use it only to send you MicroZine.

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.



Claim Your: Useful

"Arduino Software Guide"

   Right Now...





Privacy Policy | Contact | About Me

Site Map | Terms of Use



Visit our Facebook Page:

   Click Here



Sign up for MicroZine
''The'' Microcontroller Newsletter

Enter your first Name and primary email address in the form below:


And receive absolutely FREE a full project for:

"Measuring Analogue Voltages
Without An ADC"

(Using only one pin).

Instant Download:
You Can
Get It Right Now

Warning: This project could be  Removed 
at any time.  

It will  NOT be 
available indefinitely SO
To avoid 
disappointment  get it:

Now



:
:
Don't worry -- your e-mail address is totally secure. I promise to use it only to send you MicroZine
Remember this is a project with full description and fully debugged C Source code - and it's not available from the main website.

You can only get it through this newsletter.

To get exclusive access Enter your first name Name and primary email address Now in the form above.:



But wait !

There's more...

You'll receive more
free and exclusive reports as well as site information and site product updates


Scroll up to the form above and sign up NOW. Don't forget it's FREE and if you don't like it, you can unsubscribe at any time.

Click Here Now to use the form above to get your Valuable information absolutely free.



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

Recent Articles

  1. How to use the DHT22 (or DHT11) with an Arduino; full code and description. Also including a comparison of the DHT11 vs DHT22.

    The Essential Guide to the DHT22/11 humidity sensor including a library code guide for the Arduino. Learn how to determine Humidity, Dew point and Heat Index.

    Read more

  2. How to Use the MAX7219 to drive an 8x8 LED display Matrix on the Arduino.

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

    Read more

  3. How to use a DS18B20 (single or multiple on one wire) for temperature measurement using the Arduino Uno.

    How to Easily Use the DS18B20 Maxim One-Wire thermometer with Arduino example code showing external or parasitic power modes.

    Read more