Malloc function (dynamic memory allocation) resulting in an error when it is used globally

前端 未结 3 363
天涯浪人
天涯浪人 2020-12-05 12:18
#include
#include
char *y;
y=(char *)malloc(40); // gives an error here
int main()
{
    strcpy(y,\"hello world\");
}
<
3条回答
  •  离开以前
    2020-12-05 12:40

    You can't execute code outside of functions. The only thing you can do at global scope is declaring variables (and initialize them with compile-time constants).

    malloc is a function call, so that's invalid outside a function.

    If you initialize a global pointer variable with malloc from your main (or any other function really), it will be available to all other functions where that variable is in scope (in your example, all functions within the file that contains main).

    (Note that global variables should be avoided when possible.)

提交回复
热议问题