Re: General method for dynamically allocating memory for a string
- From: websnarf@xxxxxxxxx
- Date: 31 Aug 2006 09:27:32 -0700
smnoff wrote:
I have searched the internet for malloc and dynamic malloc; however, I still
don't know or readily see what is general way to allocate memory to char *
variable that I want to assign the substring that I found inside of a
string.
The C language makes this a bigger pain in the ass than it needs to be
as the discusion that has followed this shows. You can see how this is
done more easily in the Better String Library which you can get here:
http://bstring.sf.net/
If you just want to do it directly then:
#include <stdlib.h>
#include <string.h>
char * substralloc (const char * src, size_t pos, size_t len) {
size_t i;
char * substr;
if (NULL == src || len < pos) return NULL; /* Bad parameters */
for (len += pos, i = 0; i < len; i++) {
if ('\0' == src) {
if (i < pos) i = pos;
break;
}
}
i -= pos;
if (NULL != (substr = (char *) malloc ((1 + i) * sizeof (char)))) {
if (i) memcpy (substr, src+pos, i);
substr[i] = '\0';
}
return substr;
}
So if there is an error in the meaning of the parameters or if there is
a memory allocation failure then NULL is returned. If you ask for a
substring which is beyond the end of the source string, or whose length
exceeds the end othe source string, then the result is truncated.
--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/
.
- Follow-Ups:
- Prev by Date: Re: Holidays are over
- Next by Date: Re: c code reusability
- Previous by thread: Re: General method for dynamically allocating memory for a string
- Next by thread: Re: General method for dynamically allocating memory for a string
- Index(es):
Relevant Pages
|