4

Okay, say I have a sequence "abcdefg" and I do

char* s = strdup("abcdefg");
char* p;
char* q;
p = strchr(s, 'c');// -> cdefg
q = strchr(p, 'd');// -> defg

And I want to display s - p basically abcdefg - cdefg = ab, can I do this using pointer arithmetic?

C. Cristi
  • 569
  • 1
  • 7
  • 21

3 Answers3

7

You can do:

printf("%.*s", (int)(p - s), s);

This prints s with a maximum length of p - s which is the number of characters from s to p.

M.M
  • 138,810
  • 21
  • 208
  • 365
1

You cannot. The string is saved as a sequence of letters ending in a zero byte. If you print a pointer as a string, you will tell it to print the sequence up to the zero byte, which is how you get cdefg and defg. There is no sequence of bytes that has 'a', 'b', 0 - you would need to copy that into a new char array. s - p will simply give you 2 (the distance between the two) - there is no amount of pointer arithmetic that will copy a sequence for you.

To get a substring, see Strings in C, how to get subString - copy with strncpy, then place a null terminator.

Amadan
  • 191,408
  • 23
  • 240
  • 301
1

Okay, if you need to cut p from s, the following code should work:

char s[100];  // Use static mutable array
strcpy(s, "abcdefg");  // init array (ok, ok I dont remember the syntax how to init arrays)
char* p = strchr(s, 'c');// -> cdefg
*p = 0;  // cut the found substring off from main string
printf("%s\n", s); // -> ab
grapes
  • 8,185
  • 1
  • 19
  • 31