c - return substring of string -
i have large string, want use pieces of don't want copy them, figured can make structure marks beginning , length of useful chunk big string, , create function reads it.
struct descriptor { int start; int length; }; so far good, when got writing function realized can't return chunk without copying memory...
char* getsegment(char* string, struct descriptor d) { char* chunk = malloc(d.length + 1); strncpy(chunk, string + d.start, d.length); chunk[d.length] = '\0'; return chunk; } so questions have are:
- is there way can return piece of string without copying it
- if not, how can deal memory leak, since copy in heap memory , don't have control on call
getsegment?
answering 2 questions:
- no
- the caller should provide buffer copied string
- i pass pointer descrpiptor
char* getsegment(const char* string, const char *buff, struct descriptor *d)
Comments
Post a Comment