0

I am trying to write a function which passes on a text and which returns only one line (main objective to check if a character string is in a line if yes to print it if not not to print it) my function get line thus receives character after character thanks to getchar and if the character entered is \ n then get char returns the line. here is what i tried to do:

char get_line(){
    int i=0;
    char c;
    char *s=malloc(MAX_LINE*sizeof (char));
    char s[MAX_LINE];
    while ((c=getchar())!=EOF){
        if (c!='\n'){
            s[i]=c;
            i++;
        }
        else{
            s[i]='\0'
        }
            return s;
        }
    s[i]='\0';
    return s;
}

I don't want a code that works better but an explanation why my code does not work

  • 4
    `s[]` is a local variable that dies when you return from the function. Anyway the function is supposed to return `int`. Please see [Function returning address of local variable error in C](https://stackoverflow.com/questions/22288871/function-returning-address-of-local-variable-error-in-c) – Weather Vane Mar 23 '21 at 08:56
  • 1
    So many issue, you are returning an int, `s` is in the stack, so you shouldn't return s, you need to allocate memory or get a buffer as function param. – Ôrel Mar 23 '21 at 08:58
  • Use `char *s = malloc(...)` instead for example. In this case, the local variable is `s` itself, i.e. a pointer to the allocated memory. – Damien Mar 23 '21 at 08:58
  • 1
    Missing `}`, probably meant to go just before the last `s[i]='\0'`? – Tony Mar 23 '21 at 08:58
  • Also `char c` should be `int c`. Function `getchar()` does not get a `char`. It is counter-intuitive, but C functions almost invariably use `int` to pass and return characters. – Weather Vane Mar 23 '21 at 08:58
  • 1
    `;` are missing also. Activate warning when you compile your code – Ôrel Mar 23 '21 at 08:59
  • is it better now? – Doron Slomovits Mar 23 '21 at 09:15
  • @DoronSachaSlomovits No, it's not better now. Now you have two variables with the same name. Surely the compiler gives you an error about that. If you add `char *s = malloc...`, you need to delete the line `char s[MAX_LINE]` – William Pursell Mar 23 '21 at 09:54
  • You also need to add a check that `i < MAX_LINE` or you will overflow the buffer. You either need to abort when i is too large, or reallocate the buffer to make space. – William Pursell Mar 23 '21 at 09:55
  • As written, this function returns in the loop body on the first iteration. You should either move the inner return into the if condition, or delete it and add a break in the if. – William Pursell Mar 23 '21 at 09:58

0 Answers0