C sub string

Is there possible the sub string without allocing and without change the original array?

like:

1
2
char*orig="original";
char*sub=&orig[4];
Last edited on
not possible...
well I have alternative solution but here need allocing outside of procedure


1
2
3
void c_substr(char*out,const char*str,long starts,long ends){
    memcpy(out,&str[starts],(ends-starts)+1);
};
Last edited on
Don't forget to null-terminate.
Is there possible the sub string without allocing and without change the original array?

Yes, what you've done is fine. You can also express the same thing using pointer arithmetic:

1
2
char* orig = "original";
char* sub = orig + 4;

Things to remember:

- If you change the contents of sub, you'll also change the contents of original.

- You haven't NULL-terminated your string, so both orig and sub are going to be problematic if you try and do any string manipulation.
Last edited on
^^ Tomets strings are null terminated
> ^^ Tomets strings are null terminated

Yes, the string literal is null terminated. But the null terminated sequence is a sequence of const chars.

1
2
3
4
5
6
// char* orig = "original" ; // **** bad ****
const char* orig = "original" ; // fine
const char* sub = orig+4 ; // also fine

char* bad = "original" ; // **** bad
bad[2] = 'G' ; // **** terrible, results in undefined behaviour 
Tomets strings are null terminated
Yes, the string literal is null terminated. But the null terminated sequence is a sequence of const chars.

Huh... shows how long it's been since I worked with C-style strings. I forgot that's how they worked. I work pretty much exclusively with std::string these days, with the occasional smattering of wxString...

Apologies to any readers for the misinformation.
Last edited on
@Tomhet

Is there possible the sub string without allocing and without change the original array?

like:

1
2
 char*orig="original";
char*sub=&orig[4];




1
2
3
4
const char *orig = "original";
const char *sub  = orig;

while ( *sub ) std::cout << sub++ << std::endl;



You will get a sequence of substrings.:)
Last edited on
Topic archived. No new replies allowed.