Re: General method for dynamically allocating memory for a string



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/

.



Relevant Pages

  • Re: reset char array
    ... Ok, here's the question, how to reset a char ... > array will grow further instead of being replaces. ... > It's because of subStr uses strcat and the second time I use it the test ...
    (comp.lang.c)
  • Re: struggling with strings
    ... int main{ ... extern char *strset; ... extern int substring_index(const char *string, ... //finds rightmost index of substr ...
    (comp.lang.c)
  • Re: accessing chars in a string
    ... My immediate problem was checking a specific position in a string for a ... substr works OK in that case. ... CC> How do I access specific character positions in a scalar string? ... a string char by char or to directly index for a char. ...
    (perl.beginners)