Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning string from C function

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.

like image 825
MrWolf Avatar asked Sep 12 '14 00:09

MrWolf


People also ask

Can I return a string from a function in C?

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.

Which function returns a string within a string?

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.


1 Answers

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; } 
like image 188
michaelmeyer Avatar answered Oct 13 '22 07:10

michaelmeyer