我是 C 语言的初学者。
main() {
int *a-ptr = (int *)malloc(int);
*a-ptr = 5;
printf(“%d”, *a-ptr);
}
问题是:这能保证打印 5 吗?
答案是:不,有两个原因:
- 变量名称中不能使用“-”
- “您没有分配 int 存储空间”
我不明白第二点。存储不是用这一行分配的吗?
int *a-ptr = (int *)malloc(int);
最佳答案
main() { // wrong. Should return int
int main() { // better
int *a-ptr = //wrong. no dashes in variable names
int *a_ptr = // better, use underscores if you want to have multiparted names
(int *)malloc(int); // wrong. Don't typecast the return of malloc(), also it takes a
// size, not a type
malloc(sizeof(int)); // better, you want enought memory for the sizeof 1 int
所以更好的代码版本是:
int main() {
int *a_ptr = malloc(sizeof(int));
*a_ptr = 5;
printf("%d", *a_ptr);
free(a_ptr); // When you're done using memory allocated with malloc, free it
return 0;
}
关于c - 分配int存储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13920825/