-1

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", ???);
  • 3
    You can use `%.*s` specifier to pass the length of the string you wish to print – UnholySheep Oct 27 '21 at 09:09
  • 2
    https://stackoverflow.com/questions/256218/the-simplest-way-of-printing-a-portion-of-a-char-in-c – MarcoLucidi Oct 27 '21 at 09:09
  • Two possible solutions come to my mind: 1. print the string character-by-character in a loop from start pointer to end pointer. 2. save the character after the end pointer, replace it with `'\0'`, print the string using normal string functions and restore the original character. – Bodo Oct 27 '21 at 09:09
  • If it's just for debugging purposes, the performance doesn't usually play that much of a role. Why not print characters, like in : `for (int len = 0; len < 7; ++len) printf("%c", *(pStart + len));` – Ronald Oct 27 '21 at 09:10
  • 2
    `&(pText + 6)` is wrong by the way, it should not use the pointer-to operator `&`. – Some programmer dude Oct 27 '21 at 09:15
  • 1
    You should be able to find these bugs easily by simply enabling all warnings and paying attention to them. – Lundin Oct 27 '21 at 09:30

1 Answers1

4

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621