Dark Bit Factory & Gravity
PROGRAMMING => C / C++ /C# => Topic started by: Zeb on September 20, 2008
-
Since C has no feature to extract part of a string from a string (like PHP's substr does) I thought I'd modify an existing routine...
int substr(char **tFrom,int tTo,int tOffset, int tLen) {
tTo = (char*) malloc(strlen(tFrom));
strncpy(tTo, tFrom+2, 5);
return tTo;
}
Any idea why this doesn't work?
tTo = (char*) malloc(strlen(tFrom));
^
clparse.c(47) : Error: need explicit cast to convert
from: char *
to : int
strncpy(tTo, tFrom+2, 5);
^
clparse.c(48) : Error: need explicit cast for function parameter 1 to get
from: int
to : char *
--- errorlevel 1
-
tTo = (char*) malloc(strlen(tFrom));here the input parameter "tTo" is an "int" but you assign a char* to it.
How about this?
char* substr(char *src, int start, int length)
{
char *dst;
if (length==0)
length= strlen(src+start);
dst = (char*) malloc(length+1);
memcpy(dst, src+start, length);
dst[length]=0;
return dst;
}
-
Thanks, that works!
How do you give karma? Can't find the control!
This is where I get mega confused with C - where to use pointers/references/direct access to variables :/
-
You can't give out Karma until you reach 20 or 25 posts :)
Once you do get to grips with pointers you can see why C and C++ are amazing languages!
Jim
-
The funny thing is, I already know what pointers are having coded assembler for about 10 years!
What I always found confusing is where to pass a pointer and when to pass the variable! I find C so confusing!
-
having coded assembler
you'll notice that C is in many cases very near to assembly.
today there's not much reason to use only C (except of some embedded platforms).
In C++ you'll find that alot of these kind of things are already done.
Have a look at std::string (http://www.cplusplus.com/reference/string/string) for example...
-
Thanks!
This book has [very] loosely covered variables and types, now I'm onto expressions and statements - can't wait until I hit the strings section as that's been my main cause for concern.
With assembler you can "see" exactly how a string is being handled/manipulated (especially with the help of MonAm) but C for me has been a little bit on the HELP I CAN'T FIGURE THIS OUT! side :D