-2

很抱歉这个可能很荒谬和基本的问题(我从十几岁开始就没有用 C 编程,现在我 39 岁了......),但是通过下面的代码,我得到了 tcc 编译器的输出:

test.c:15: warning: assignment makes pointer from integer without a cast
test.c:26: error: lvalue expected

为什么会发生在第 26 行?

感谢您的耐心等待,我这几天主要做web前端和后端的东西......

- - - 代码 - - -

#include <stdio.h>
// needed for gets() and puts()

char* input() {

    char inp[256];

    gets(inp);

    return inp;
}

void output(outp) {

    puts(outp);
}

int main() {

    int exe = 1;
    char inp[256];
    char exit_msg[] = "END OF PROGRAM. THANK YOU!\0";

    while(exe) {

        inp = input(); // line 26
        output(inp);

        if (inp == "END"){

            exe = 0;
        }
    }
    puts(exit_msg);

    return 0;
}
4

1 回答 1

3

There's so much wrong ...

  1. Don't use gets, ever. It's been removed from C because it's impossible to use safely. (If the input is too long, you have a buffer overflow on your hands.) You could use e.g. fgets instead.

  2. input() returns the address of a local variable. Local variables are destroyed when they go out of scope, i.e. when input returns. The return value is always garbage.

  3. outp is missing a type. Looks like you're getting implicit int from your compiler (implicit int has been removed from C in 1999).

  4. String literals are implicitly NUL-terminated. \0 doesn't do much in "END OF PROGRAM. THANK YOU!\0" (except making sure there are two NULs at the end).

  5. You cannot assign to arrays in C. inp = ... is invalid. Check out strcpy and memcpy. (Even if you could assign to arrays, inp = input() would be a type error because input returns a pointer, not an array (but you can't return arrays).)

  6. inp == "END" compares pointers. inp will never have the same address as a string literal. Check out strcmp.

  7. Why does exe exist? Instead of setting exe = 0, you could just break out of the loop.

(#5 is the one your question is about.)

于 2018-05-12T15:38:44.923 回答