简体   繁体   中英

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???

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 */

replace : x[i] = (char)i; to: x[i]=(char) ( ((int) '0') + i ); and add x[11] = '\\0';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM