Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying pointer substraction

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?

like image 730
C. Cristi Avatar asked Jan 02 '23 11:01

C. Cristi


2 Answers

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.

like image 149
M.M Avatar answered Jan 04 '23 00:01

M.M


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.

like image 36
Amadan Avatar answered Jan 04 '23 00:01

Amadan