Length of the string from address of variable(&variable) - Embedded C

843 views Asked by At

How can I find the length of the string from address of variable(&variable) ? Below is the code :

SimpleProfile_GetParameter(SIMPLEPROFILE_CHAR7, &newValue); // Hello123
const char echoPrompt[] = "Print From BLE characters:\r\n";
UART_write(uart, echoPrompt, sizeof(echoPrompt)); // Output : Print From BLE characters: | Size : 29
UART_write(uart, &newValue, sizeof(&newValue)); // Output : Hello | Size : 4

I am using this code in Code Composer Studio (CCS). I need to print the string in UART, Where I need to specify number of character in the string.

I need "Hello123" to be printed instead its printing "Hello"

1

There are 1 answers

7
Barmar On BEST ANSWER

&newValue is a pointer, so sizeof(&newValue) returns the size of a pointer, not the string it points to. Assuming newValue is a null-terminated string, use strlen().

sizeof operates at compile time, it can't get the size of a string that's constructed dynamically.

You should also do that with echoPrompt, because sizeof includes the trailing null byte, and you probably don't need to write that.

UART_write(uart, echoPrompt, strlen(echoPrompt));
UART_write(uart, &newValue, strlen(&newValue));