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

前端 未结 3 366
天涯浪人
天涯浪人 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:39

    You cannot use a function call when initializing a static or global variable. In the following code sequence, we declare a static variable and then attempt to initialize it using malloc:

    static int *pi = malloc(sizeof(int));

    This will generate a compile-time error message. The same thing happens with global variables but can be avoided for static variables by using a separate statement to allocate memory to the variable as follows. We cannot use a separate assignment statement with global variables because global variables are declared outside of a function and executable code, such as the assignment statement, must be inside of a function: static int *pi; pi = malloc(sizeof(int));

    From the compiler standpoint, there is a difference between using the initialization operator, =, and using the assignment operator, =.

提交回复
热议问题