| TIP: Click on subject to list as thread! | ANSI |
| echo: | |
|---|---|
| to: | |
| from: | |
| date: | |
| subject: | Pointers |
Hello Darin!
02 Sep 03 21:31, you wrote to me:
DM>>> Yes. But not in C. Okay, that's not entirely true - you'd have
DM>>> to make significant changes, which are not always an option. If
DM>>> you wrote both the caller and callee, then these changes are
DM>>> what I'd suggest anyway, even in C++.
BS>> Hmm.. I looks like it would be easier with the extra pointer.
DM> Personal preference, I suppose. However, the method I proposed below,
DM> despite being "more difficult", is, I believe, usually the better
DM> choice.
DM> 1. It is fast. With no malloc/free (slow, expensive function calls),
DM> it performs as fast as the caller allows. The only thing that would
DM> be faster is if we didn't need to copy at all, e.g.: char const*
DM> test() { return "test"; } . There are some other
speed-ups possible
DM> (e.g., caching the length of the string being copied so that the next
DM> time we're called, we don't need to recalculate it), but overall it's
DM> very fast.
Yes that's right! A const char*, should not require memory allocation afaik?
DM> 2. It is complete safe. Since we check the size of the incoming
DM> buffer, we know we won't overwrite anything.
DM> And, of course, it's a bit more than needed.
Yes.
KK>>>>> #include
KK>>>>> #include
DM>>> char* test(char** buf, size_t buflen)
DM> We don't need the extra * on buf throughout here. So this would be
DM> char* buf ...
I saw so, but I forgot to ask.
KK>>>>> {
DM>>> /* char* tmp = (char*)malloc(80); */
DM>>> /* if(tmp) sprintf(tmp, "test"); */
DM>>> char* source = "test";
DM>>> if (buflen > strlen(source))
DM>>> sprintf(*buf, source);
DM> And this would just be buf, not *buf...
Indeed.
DM>>> /* return tmp; */
DM>>> return *buf;
DM> As would this ....
Well it doesn't matter? It would return the address anyway.
KK>>>>> }
KK>>>>> int main()
KK>>>>> {
DM>>> char buf[16];
DM>>> printf("%s\n", test(buf, sizeof(buf)));
KK>>>>> fgets(buf, 16, stdin);
KK>>>>> return 0;
KK>>>>> }
DM>>> No malloc/free's here.
BS>> No i see thank you :)
DM> No problem.
:-)
Regards,
Bo
--- Squish/Linux v1.12.002 BETA
* Origin: The Night Express, Roennede Dk (2:236/100)SEEN-BY: 633/267 270 @PATH: 236/100 237/9 20/11 106/1 2000 633/267 |
|
| SOURCE: echomail via fidonet.ozzmosis.com | |
Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.