如何打印两个指针之间的字符串?

-1 c string printf pointers

我正在为埃隆·马斯克建造一枚火箭,内存使用对我来说非常重要。

我有文本和指向它的指针pText。堆里很冷。

有时我需要分析字符串及其单词。我不在堆中存储子字符串,而是存储两个指针 start/end 来表示文本的子字符串。但有时我需要打印这些子字符串以进行调试。我怎么做?

我知道要打印字符串我需要两件事

  • 指向乞讨的指针
  • 末尾为空终止符

有任何想法吗?

// Text
char *pText  = "We've sold the Earch!";

// Substring `sold`
char *pStart = &(pText + 6) // s
char *pEnd   = &(pStart + 3) // d

// Print that substring
printf("sold: %s", ???);
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 5

如果您只想打印子字符串,请使用精度参数printf

printf("sold: %.*s", (int) (pEnd - pStart) + 1, pStart);
Run Code Online (Sandbox Code Playgroud)

如果您需要以其他方式使用子字符串,那么最简单的可能是创建一个临时字符串,复制到其中,然后打印它。

也许是这样的:

// Get the length of the sub-string
size_t length = pEnd - pStart + 1;

// Create an array for the sub-string, +1 for the null-terminator
char temp[length + 1];

// Copy the sub-string
memcpy(temp, pStart, length);

// Terminate it
temp[length] = '\0';
Run Code Online (Sandbox Code Playgroud)

如果您需要多次执行此操作,我建议您为此创建一个通用函数。

malloc您可能还需要根据用例动态分配字符串。