字符串从变量(&变量)地址的长度 - 嵌入式C

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

本文关键字:变量 嵌入式 地址 字符串      更新时间:2023-10-16

如何从变量(& variable)地址找到字符串的长度?以下是代码:

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

我在代码作曲家Studio(CCS)中使用此代码。我需要在UART中打印字符串,我需要在其中指定字符串中的字符数。

我需要打印" Hello123",而不是打印其" Hello"

&newValue是一个指针,因此sizeof(&newValue)返回指针的大小,而不是指向的字符串。假设newValue是一个null终止的字符串,请使用strlen()

sizeof在编译时间运行,它无法获得动态构造的字符串的大小。

您也应该使用echoPrompt来执行此操作,因为sizeof包括尾随的null字节,您可能不需要写。

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