[Courses] [C Doubt]
Akkana
akkana at shallowsky.com
Wed Sep 18 21:58:16 EST 2002
sneha writes:
> **thank u :)
> anyway... I wrote my own function...
> friendly
One comment on your function, in case you're interested:
> char *substr(char *str,int s,int e)
> {
> int i,j=0;
> char *str1;
> str1=(char *)malloc(strlen(str));
> for(i=s-1;i<e;i++,j++)
> str1[j]=str[i];
> return str1;
> }
This works fine, but you're allocating more memory than you need ...
you really only need (e - s + 1) bytes (+1 because you'll probably
want to write a null at the end, since most functions that take strings
expect them to be null-terminated). This also has the nice bonus
of making the function a little faster since you don't need to call
strlen() (which has to loop over str to find out how long it is).
So I'd suggest modifying your function very slightly:
str1=(char *)malloc(e-s+1);
for(i=s-1;i<e;i++,j++)
str1[j]=str[i];
str1[j]='\0';
return str1;
...Akkana
More information about the Courses
mailing list