我们如何使用head代替struct node? [英] How can we use head in place of struct node?

查看:223
本文介绍了我们如何使用head代替struct node?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个函数在链表中创建一个节点,它以一个整数作为参数,当我使用这个函数时我的程序运行正常,但我怀疑是在这里使用的malloc



我尝试过:



我的结构是

i made a function to create a node in linked list which takes a integer as argument ,my program is running fine when i am using this function but my doubt is in malloc used here

What I have tried:

my structure is

struct{
int data;
struct node*}



这是我的插入函数


this is my insert function

void insert(int x){
struct node *temp=(struct node*)malloc(sizeof(struct node));
temp->data=x;
temp->next=head;
head=temp;

}



注意我将head声明为全局变量


note i declared head as a global variable as

struct node* head;



显然head是一个指针变量(指向struct node的指针),它在内存中只占用4个字节
,而(struct node)将在内存中占用8个字节

当我在sizeof运算符中使用head而不是struct node时,我怀疑这是什么?


clearly head is a pointer variable(pointer to struct node) which will take only 4 bytes
in memory whereas (struct node) will take 8 bytes in memory
my doubt is this when i am using head in sizeof operator instead of struct node that is

struct node *temp=(struct node*)malloc(sizeof(head));

我没有收到任何错误

没有警告并得到前面的确切答案但是head(4bytes)和struct node(8)的内存分配会有所不同它应该影响我的程序??

i am getting no error
no warning and getting the exact answer as was before but memory allocation will be different for head(4bytes) and struct node(8 bytes) it should affect my program??

推荐答案

你的结构总是比指向它的指针大:如果只是因为实际节点包含指向结构的指针所以它必须至少是指针的大小加上其他元素的大小。



所以是的,你必须使用 sizeof( struct node)当你 malloc 节点本身时。

如果你不这样做,那么你会遇到问题。 ..但你可能没有注意到它们在开发中取决于两个因素:相邻节点的打包,以及 malloc 函数的粒度,这通常不是你的想法:一些系统总是以8或16字节块的倍数分配内存,所以你的代码可以工作......直到你的编译器或它的选项发生变化......:笑:



总是要求合适的尺寸:永远不要靠效果让你走出一个洞!
Your structure will always be bigger than the pointer to it: if only because the actual node contains a pointer to the struct so it has to be at least the size of a pointer plus the size of the other elements.

So yes, you must use sizeof(struct node) when you malloc the node itself.
If you don't then yes you will get problems ... but you may not notice them in development depending on two factors: the packing of adjacent nodes, and the granularity of the malloc function, which is often not what you think: some systems will always allocate memory in multiples of an 8 or 16 byte chunk , so your code works ... until your compiler or it's options changes ... :laugh:

Always ask for the right size: never rely on "effects" to get you out of a hole!

这篇关于我们如何使用head代替struct node?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆