1

I'm trying to send an array of characters in C, byte by byte to an output for a microcontroller. I'm using the following code:

int main() {
...
   LogOutput("Hello World!");
}

void LogOutput(char *msg) {

    int i;
    for (i = 0; i < sizeof(msg); i++) {
        USART0_TX(msg[i]);              // transmit byte
    }
}

However, this only sends the first two letters "He" --- does anybody know what I'm doing wrong?

pb2q
  • 58,613
  • 19
  • 146
  • 147
codedawg82
  • 466
  • 1
  • 12
  • 25

2 Answers2

5

You're using the sizeof operator, and getting the size of the datatype, not the length of the string. Use strlen to get the length of a string (include string.h for strlen and other string manipulation functions).

pb2q
  • 58,613
  • 19
  • 146
  • 147
  • Thanks! #include as well for n00bs like myself out there! – codedawg82 Jul 16 '12 at 19:52
  • fyi, i also found that if you're working with microcontrollers like I am, this won't work with char arrays that contain a 0x00 as the strlen function terminates on a NULL character. best to just pass the length as a separate parameter for those cases. – codedawg82 Jul 18 '12 at 17:29
1
int main() {
...
   LogOutput("Hello World!");
}

void LogOutput(char *msg) {

    int i;
    for (i = 0; i < strlen(msg); i++) {
        USART0_TX(msg[i]);              // transmit byte
    }
}
pb2q
  • 58,613
  • 19
  • 146
  • 147
windstrome
  • 11
  • 1