NerdKits - electronics education for a digital generation

You are not logged in. [log in]

NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.

Microcontroller Programming » char array if statement

February 23, 2014
by escartiz
escartiz's Avatar

Hi everyone, I need help with if else validation of a char array, I have hooked up a keypad to the mcu and I am gathering inputs as char arrays so for example I have:

char buf[5];
buf[0] = 0;

then as I get inputs I assing them as follow

 buf[0] = 1; buf[1] = 3; etc...

Once I gather all 5 arrays for buf[] I like to do an if else evaluation to find out if the whole buf[0-5] is equal to "12345" else set buf to blank again

if(buf[] == '12345') { // continue } else { buf[0] = 0x00; }

this is not working, so what would be the best way to do a full evaluation of buf[] I was thinking of using &&

if((buf[0] == 1) && (buf[1] == 2) && (buf[2] == 3)….);

but before I try that as it would look messy I like to know the best approach to accomplish this

April 21, 2014
by BobaMosfet
BobaMosfet's Avatar


It's a string. Terminate it and just use a string function.


April 21, 2014
by JimFrederickson
JimFrederickson's Avatar

For a ittle more information...

In the c Language Srings are by definition "arrays of characters terminated with a

In order for you to use the "string functions" on your "char arrays" you will need to
make sure that your "char arrays" are "the maximum size/count of char's that you would
put into them plus 1 additonal char that is a null, 0 value". (NOTE: The null terminater is "required", if you don't have one in your array then the string functions will tramp-along thru consecutive memory until it finds one...)

Then your "char arrays" can be treated/used as strings.

If you go to "where-ever your WinAVR Folder is" then from there "avr/include" you will
find "string.h". You can see the list of "string functions there. (They are further
defined in the documentation, but you may find the include file useful as well.)

April 21, 2014
by Noter
Noter's Avatar

Hmm, I don't remember seeing this post 8 weeks ago. Anyway, memcmp() is a good function for testing values in fixed length character arrays. Don't have to worry about the null terminators because you give it the length. AVR Libc memcmp()

Post a Reply

Please log in to post a reply.

Did you know that you can make a capacitive proximity sensor with some aluminum foil and paperclips? Learn more...