c - C 编程使用 malloc 和赋值
问题描述
我是 C 编程新手。我正在为一个需要我使用 malloc 的学校项目工作。
我的问题是:在分配指针之前还是之后调用 malloc 更好
例如:
struct Node{
int value;
struct Node* next;
}
int main(int argc, char** argv){
struct Node* mylist = //something
//which of the following is the correct way to do this?
struct Node* node = mylist;
node = (struct Node*) malloc(1 * sizeof(struct Node));
//or
struct Node* node = (struct Node*) malloc(1 * sizeof(struct Node));
node = mylist;
}
解决方案
你想要这样的东西:
struct Node{
int value;
struct Node* next;
}
int main(int argc, char** argv){
struct Node* mylist; // declare the mylist pointer, it points nowhere right now
mylist = malloc(1 * sizeof *mylist); // roughly the same as "1 * sizeof(struct Node)"
// now mylist points to a memory region of
// size (1 * sizeof(struct Node))
// do something
mylist->value = 1234;
.....
// once you're done
free(mylist);
// now mylist points nowhere again
}
我建议您阅读 C 教科书中有关指针和动态内存分配的章节。
推荐阅读
- python - 使用 pytest 对返回值的 void 方法进行单元测试
- git - 如何撤消 git restore 以取回更改
- flutter - 颤动的 ProgressDialog 似乎有影响所有实例的静态字段
- r - 如何合并具有对象名称中匹配字符的数据框?
- java - Java 泛型异常
- regex - Redshift psql regex如何匹配连续重复的数字?
- rust - 有没有办法在 Warp 中作为过滤器的一部分进行验证?
- python - Pygame 显示黑屏(《Pro Python 最佳实践》)
- python - Scrapy - 无法从 xpath/css 获取输出
- laravel - 我想将数据插入数据库但未定义的索引错误显示