c - 分配int存储?

标签 c pointers memory-management

我是 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/

相关文章:

c++ - const-correctness 是否给编译器更多的优化空间?

pcap_loop 的最后一个参数中的编译器警告。指向不同大小的整数

c++ - 不使用 malloc 是否有可能造成内存泄漏?

c - 使用 -std=c99 编译时,我需要使用 -pedantic 还是 -ansi?

c - c中的windows服务代码,在哪里编写服务逻辑代码?

c - Linux 上的汇编编译器。纳斯姆还是AS?

c++ - 在指针 : Reading 4 bytes given uint8_t pointer memory start location and size 中搜索值

memory-management - 将 Box 中的大值复制到 Rust 中的 Vec 中,而不会破坏堆栈

objective-c - 为什么在下面的代码中保留计数显示为 2?

C Tcl 命令不被识别