I haven't used C in over 3 years, I'm pretty rusty on a lot of things.
I know this may seem stupid but I cannot return a string from a function at the moment. Please assume that: I cannot use string.h
for this.
Here is my code:
#include <ncurses.h> char * getStr(int length) { char word[length]; for (int i = 0; i < length; i++) { word[i] = getch(); } word[i] = '\0'; return word; } int main() { char wordd[10]; initscr(); *wordd = getStr(10); printw("The string is:\n"); printw("%s\n",*wordd); getch(); endwin(); return 0; }
I can capture the string (with my getStr
function) but I cannot get it to display correctly (I get garbage).
Help is appreciated.
Strings in C are arrays of char elements, so we can't really return a string - we must return a pointer to the first element of the string. All forms are perfectly valid.
The function strstr returns the first occurrence of a string in another string. This means that strstr can be used to detect whether a string contains another string.
Either allocate the string on the stack on the caller side and pass it to your function:
void getStr(char *wordd, int length) { ... } int main(void) { char wordd[10 + 1]; getStr(wordd, sizeof(wordd) - 1); ... }
Or make the string static in getStr
:
char *getStr(void) { static char wordd[10 + 1]; ... return wordd; }
Or allocate the string on the heap:
char *getStr(int length) { char *wordd = malloc(length + 1); ... return wordd; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With