我刚刚被介绍给 C 中的指针,并且一直在玩弄它们以尝试更熟悉它们。
有人可以向我解释为什么下面的代码无法编译吗?
int *high = (int *)malloc(sizeof(int)),*low = (int *)malloc(sizeof(int));
*high = 100;
*low = 0;
If you have #included stdlib.h it should compile.
To ensure that your code is correct, replace it with this:
#include <stdlib.h>
int *high = malloc(sizeof(int));
int *low = malloc(sizeof(int));
if(high == NULL || low == NULL)
{
// no memory, error handling here
}
*high = 100;
*low = 0;
...
free(high);
free(low);
Wrapping the code like shown below whould make it compile and work as expected:
#include <stdlib.h>
int main()
{
int *high = malloc(sizeof(int)),*low = malloc(sizeof(int));
*high = 100;
*low = 0;
return 0;
}
Anyway, the code lacks error checking on system calls. Always check the return value of system calls, In the case of malloc()
a value of NULL
would be returned if memory could not have been allocated as requested. In such case the line
*high = 100;
would most likely cause the program to crash, as dereferencing *NULL
provokes undefined behavior.
In C it is not necessary to cast functions returning a value of void*
. Even more it is not recommended to do so, as doing so might hide errors, for example if protoyping for the function in question is missing, the error/warning which would be given by the compiler without casting is surpressed if using casting.