Concatenate/append using <string.h>
hello,
i doing preparations new project. involves basic c knowledge.....
i have following test code:
i getting error message:
what doing wrong?
thanks in advance!
i doing preparations new project. involves basic c knowledge.....
i have following test code:
code: [select]
#include <string.h>
#include <stdlib.h>
//constants
const byte iputmaxlength = 30 + 1 + 1 + 1;//30 plus header plus footer plus terminating zero
const char header = '~';
const char footer = '#';
const char btnu[] = "buttonup";
const char btnd[] = "buttondown";
const char btnl[] = "buttonlefr";
const char btnr[] = "buttonright";
char stringin[iputmaxlength] = {
'\0'};
int ledpin = 13; // led connected digital pin 13
void setup(){
pinmode(ledpin, output); // sets digital pin output
serial.begin(9600);
}
void loop(){
serialread();
}
void serialread(){
// see if there's incoming serial data:
if(serial.available() > 0) {
getincomingchars();
}
serial.println(stringin);
}
void getincomingchars() {
// read incoming data char:
char charin = serial.read();
if ((strlen(stringin)) < iputmaxlength) {
strcat(stringin, charin)
}
}
i getting error message:
code: [select]
in function 'void getincomingchars()':
error: invalid conversion 'char' 'const char*'
what doing wrong?
thanks in advance!
there 2 problems in code. one problem minor , fixed. the other problem serious.
first minor problem...
strcat expects both parameters strings (arrays of characters terminated null). you passing char second parameter. something past problem...
the second (serious) problem line of code...
you not leaving space null terminator. i'll use example illustrate problem...
assume iputmaxlength = 4 , stringin has letters 'a' , 'b' stored. this memory contents...
[a]
first minor problem...
strcat expects both parameters strings (arrays of characters terminated null). you passing char second parameter. something past problem...
code: [select]
char charin[2];
charin[0] = serial.read();
charin[1] = 0;
...
strcat(stringin, charin); // note: forgot semicolonthe second (serious) problem line of code...
code: [select]
if ((strlen(stringin)) < iputmaxlength) {you not leaving space null terminator. i'll use example illustrate problem...
assume iputmaxlength = 4 , stringin has letters 'a' , 'b' stored. this memory contents...
[a]
the character 'c' arrives. strlen(stringin) = 2 less iputmaxlength strcat executed leaving this...
[a] [c]
no problem. the character 'd' arrives. strlen(stringin) = 3 less iputmaxlength strcat executed leaving this...
[a] [c] [d]
oops! strcat wrote null-terminator past end of stringin corrupting whatever next in memory.
Arduino Forum > Forum 2005-2010 (read only) > Software > Syntax & Programs > Concatenate/append using <string.h>
arduino
Comments
Post a Comment