can a function return a string?
Hi
Would the function work if it is written like this: #define BUFSIZE 256 int main(void) { char string[BUFSIZ], copyString; strncpy(copyString, getString(string), 11); ..... } char getString(char string[]) { printf("Enter a string: "); fgets(string, BUFSIZE, stdin); return *string; } Thanks |
Maybee but why would you do this?
the string passed to the function is just a pointer to the real string data. so if its modifyed in the function and the main program uses it again some where else the data would have been changed so its like it was returned with the new information. |
Two things fixed below in red.
Code:
#define BUFSIZE 256 |
i need the function readString() to read in the 10 digit number and pass it to the main() function,
so actually i don't want to "return *string", but to "return string" (not the pointer). How can i go about this? If i enter "return string", then the compiler says: warning: return makes integer from pointer without a cast |
this would be a better way to write this
Code:
|
Quote:
Quote:
Code:
char *getString(char string[]) |
Hey Hko mind my ignorance but why would you ever return a string pointer instead of just using the string that was passed ?
|
Quote:
But it seems hubabuba wants it. And a valid reason to do it could be just convenience. Some standard library functions do it: e.g: gets(), fgets(), strcpy(), strcat(),... |
By the way my code above causes wierdness in the new string created because its 256 char long if you printed it out it would print garbage after the 11th char. A way to prevent this would be needed such as maybe initlizing the array to spaces or something.
Tested in dos not linux so maybe nix dont have that issue :P |
You have to be careful with strncpy(). If you pay attention to the man page you'll find:
Quote:
|
Indeed you are the man.
strings still confuse me a bit with programming. I think memory management/ location conuses me more tho. |
Not sure if anyone cared but this is my fixed and revised code that works properly with this method and also you can change the length of the string and the copy length as well
tested on dos in emulated environment with Turbo c v. 2.0 Code:
/* Testing out some programming code to copy a string over */ |
Another implementation
Code:
|
In the red shows possible unessisary code. Reason it is is because it wont matter. The last char gets replaced by \0 regardless if its actually in the buffer or not. Ither way tho i dont belive it would use more or less memory ither way.
Code:
|
All times are GMT -5. The time now is 10:17 PM. |