cwhile-loopprintfgetcharfunction-definition

Passing character array to a function returns warning


Currently completing my C homework for the week and i'm messing about with pointers for the first time properly.

We are told to create a main function to deal with our readLine function thats premade for us (we edit a few things, like the if statement in the while loop).

When trying to compile i am given the error "/usr/include/stdio.h:356:43: note: expected ‘const char * restrict’ but argument is of type ‘int’ 356 | extern int printf (const char *__restrict __format, ...);

What would i have to do to fix this? I think its something to do with how im calling readLine. Thanks!

#include <stdio.h>

int readLine(char *s, int MAX){
    char c;
    int i = 0;
    while ((c = getchar()) != '\n' && i<MAX){
        if (*s >= MAX){
            printf("input too long!");
            return -1;
        }
        c = *(s+i);
    }
    s[i] = '\0';
    return i;
}

int main(){
    int MAX = 20;
    char s[MAX];
    printf(readLine(s, MAX));
}


Solution

  • The function returns an integer but you are going to output a string. So write

    readLine(s, MAX);
    puts( s );
    

    Also this if statement

        if (*s >= MAX){
    

    does not make sense.

    And instead of

    c = *(s+i);
    

    you have to write

    *(s+i) = c;
    

    And within the while loop you need to increase the variable i.