GCC Complaint — Assignment makes integer from pointer without a cast

后端 未结 1 721
谎友^
谎友^ 2020-12-12 07:13

I am trying to strip off the trailing \\n char that fgets() appends. I am replacing this character with a string terminating char, \\0

1条回答
  •  醉梦人生
    2020-12-12 07:25

    Your problem lies with the statement:

    word[strlen(word) - 1] = "\0";
    

    This is trying to assign the pointer to the C string to the array element, an integral type char, hence the error message "Assignment makes integer from pointer without cast".

    What you should have written was:

    word[strlen(word) - 1] = '\0';
    

    which assigns a character to the array element.

    As an aside, you should watch out for lines that are longer than (about) 100 characters. You'll only read the first part of the line, it won't have a newline at the end, and you'll read the rest of the line as a separate line next time through your loop (and this may happen many times if you have a line that is, for example 1K long).

    For what it's worth, you can fix those problems with code along the following lines:

    if ((s = strlen (word)) > 0) {
        if (s[s-1] != '\n') {
            // Line was too long, do something intelligent.
        } else {
            s[s-1] = '\0';
        }
    }
    

    0 讨论(0)
提交回复
热议问题