Home > database >  How do I print a string between two pointers?
How do I print a string between two pointers?

Time:10-27

I'm building a rocket for Elon Musk and the memory usage is very important to me.

I have text and a pointer to it pText. It's chilling in the heap.

Sometimes I need to analyse the string, its words. I don't store substrings in heap, instead I store two pointers start/end for represeting a substring of the text. But sometimes I need to print those substrings for debugging purposes. How do I do that?

I know that for a string to be printed I need two things

  • a pointer to the begging
  • null terminator at the end

Any ideas?

// 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", ???);

CodePudding user response:

If you only want to print the sub-string, then use a precision argument for printf:

printf("sold: %.*s", (int) (pEnd - pStart)   1, pStart);

If you need to use the sub-string in other ways then the simplest is probably to create a temporary string, copy into it, and then print that instead.

Perhaps something like this:

// 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';

If you need to do this many times I recommend you create a generic function for this.

You might also need to dynamically allocate the string using malloc depending on use-case.

  • Related