//print data to buffer
#define buf1Max 256
char buf1[buf1Max];
char data[30];
int bufIndex = 0;
void dataToBuffer(){
for (int x = 0; x < strlen(data); x++){ //data to buffer
if (bufIndex < buf1Max){
Serial.println(bufIndex);
buf1 [bufIndex] = (data[x]);
bufIndex++;
}//end if bufIndex
}//end for dataToBuffer
} //end void dataToBuffer
void setup() {
Serial.begin(9600);
sprintf(data,"%d",12000);
for (int x = 0; x < 200; x++){ //save data to buffer, more than buffer1 length.
dataToBuffer();
}
Serial.println(buf1);
Serial.println(strlen(buf1));
}
void loop() {
// put your main code here, to run repeatedly:
}
I created a buffer with 256 chars (buf1[0 to 255] and since i typed "bufIndex < buf1Max" i would expect its gonna to fill the buffer from 0 to 255. But.. it the serial outputs this (I deleted first 251 values):
I got 261 chars, but i told the array is max 256 chars long.. Why is the array now 261 chars long, why are the last values are a mess and where the # are the chars from 255 to 261 stored?
When i change "char buf1[buf1Max]" to "char buf1[buf1Max+1]" it seems to work; i got 256 chars stored. but why do i need to make the char array one char larger? i dont want to make the buf longer then 255chars and fill it completely up with values..
Its not really about the solution.., but about what i dont understand well.
That is a dangerous way of writing code, you should avoid to write code like that. Try to solve the problem in a different way.
This is what you do:
index = 0;
for ( int i = 0; i < 200; i++)
{
for ( int j = 0; j < 5; j++)
{
if ( index < 256)
{
buffer[index] = data[x];
index++;
}
}
}
The buffer is written until the very last character. That means there is no zero-terminator. The value of "261" is not an index, that is the strlen. You can easily see that, when you change it into:
Thanks, helps. I saw itoa gives a return value, a pointer to "/0". So i tried to make it thing visible:
sprintf(buff,"%s","11111111111111111111111111");
*buff = 'a'; // puts an a in slot 0
*(buff + 2) = 'b'; // puts an b in slot 3
startIx = buff;
Serial.print("Start index position: ");
Serial.println(startIx);
retVal = itoa (anInt, buff + 15, DEC); // puts a '5' in slot 5.
Serial.print("in Array stored: ");
for(int x = 0; x < 30;x++){
Serial.write(buff[x]);
}
Serial.println("");
Serial.print("New index position: ");
Serial.println(retVal-startIx);
but.. it return the "\o" before the new value is added. I can easily find the new end with strlen ofcourse, but why does it return a value what you already know since you have to fill it in in the itoa statement?
sprintf() has some input arguments, and a pointer to where to write to. It does not care what is already in the memory location to be overwritten. You could use
sprintf(&buff[strlen(buff)], "%d", anInt);
to NOT overwrite the first n characters of buff. But there is little advantage in doing that.