Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++ is there a way to print char* from different memory locations?

Tags:

c++

I'm not sure if the question makes too much sense, so I'll try to show an example:

Imagine I had a string at memory location &s (not null terminated) and another string at memory location z (null terminated).

char s[4]; s[0] = 'a'; s[1] = 'a'; s[2] = 'a'; s[3] = 'a';
char *z = malloc(sizeof(char) * 4);
z[0] = 'a'; z[1] = 'a'; z[2] = 'a'; z[3] = '\0';
char *y = malloc(sizeof(char) * 4);
y[0] = 'a'; y[1] = 'a'; y[2] = 'a'; y[3] = '\0';

Is there a way to represent a string, u, that is the concatenation of s and z and another string, v, that is the concatenation of s and y without having to duplicate s?

I know that it's not going to be very fast at reading, but it will certainly save more memory especially with the number of repeats to be expected. Since the value of s may change separately from z and y and the changes should appear in z and v, it would certainly be more efficient to do it without cloning s if it were possible.

like image 726
Rahul Manne Avatar asked Jan 10 '23 22:01

Rahul Manne


1 Answers

The standard name for the structure you want (or that I think you want) is a rope - it's like a compound sequence of strings with a unifying interface.

This other question about ropes has some discussion of them, and a link to the SGI extension.

If you pick up an existing implementation, check that the mutability of substrings works the way you want - some may implement copy-on-write instead.

like image 69
Useless Avatar answered Jan 28 '23 13:01

Useless