Rishikesh Ayre Rishikesh Ayre -4 years ago 92
C Question

how to add characters to character array

i want add characters to a character array. my code is

char x[100];
int i;
void setup() {
Serial.begin(115200);
}
void loop() {
for ( i=0; i<11;i++)
{
x[i]=(char)i;
}
Serial.println(strlen(x));
for (i=0;i<11;i++)
{
Serial.print(x[i]);
}

delay(1000);
}


i am expecting the array to be x[0] = 0 ,x[1] = 1, x[2] = 2......x[10]=10

but the array seems to be empty as
Serial.println(strlen(x));
returns 0
and
Serial.print(x[i]);
prints nothing.
how do i add character to an array???

Answer Source

Oups, a C string is by convention a char array terminated with a null byte. All strxx functions follow this convention.

As the first character of the array is... 0, strlen finds a terminating null at index 0 and correctly says that the length of the string is 0.

In addition, all characters with code 0 to 10 (assuming ASCII) are control non printable characters.

I assume that what you wanted to do is

for ( i=0; i<11;i++)
{
  x[i]= '0' + i; /* 0 to 9 and : */
}
x[11] = '\0';   /* terminate the array with a null to make it a C string */
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download