Archived

This topic is now archived and is closed to further replies.

johnnyBravo

Possible to have method that returns string using char?

Recommended Posts

johnnyBravo    100
Im using stdio.h file read method(fgets) which requires me to use char. and i am wrapping it up in a method called read. eg char string[100]; string = file.read(); the problem is i cant do this char read()[100] or char read()[] something like that. is there way to store a string with chars in a method? Thanks

Share this post


Link to post
Share on other sites
thec    212
Well you have a classic problem on your mind here.

You can send in the array as a (char*), but you will not know how many bytes are allocated in that array, so out of bounds memory writes are easy.

"Best" way to do this is to send in the maximum size you can fill up, like:

void read(char* pDestination, long pMaxLength) {

}

...when you know the limits... however, string managment isn't the easiest part to learn in c.

Personally, I'd recommend you to look up the STL and the std::string template.

Edit: Of course, you will call the function with: read(string,100);

Good luck
Albert

[edited by - thec on October 12, 2003 6:42:58 AM]

Share this post


Link to post
Share on other sites
superpig    1825
Yup, that''s the best solution. If there were a way of returning a 100-byte string from a function, it''d be wasteful - because you''d then have to do a byte-for-byte copy of that 100-byte string to your own ''string'' buffer. It''s better to write directly into your buffer by passing it to the function, than to use assignments.

Superpig
- saving pigs from untimely fates, and when he''s not doing that, runs The Binary Refinery.
Enginuity1 | Enginuity2 | Enginuity3 | Enginuity4
ry. .ibu cy. .abu ry. dy. "sy. .ubu py. .ebu ry. py. .ibu gy." fy. .ibu ny. .ebu

Share this post


Link to post
Share on other sites