使用节点地址的链表大小
Size of linked list using the addresses of nodes
榜单:
struct list{
int Id;
short Value;
struct list *next;
};
所以我想通过使用节点的地址来找出列表的大小(不使用 sizeof)。每个节点彼此不同 24 bytes.This 是我为此目的编写的代码:
struct list *tmp;
int sum=0;
for(tmp=ptr; tmp!=NULL; tmp=tmp->next){
sum = sum + tmp->next - tmp;
}
printf("\nThe size of the list in bytes is:%d", sum);
tmp 是指向列表的指针。 ptr 是指向列表头部的指针。我使用 tmp 是因为稍后我的 code.When 需要 ptr 我执行上面的命令我得到这个:列表的大小(以字节为单位)is:143132...。每次的数字都不一样,但不是我想要的
So i want to find out the size of the list(without using sizeof) just by using the adresses of the nodes.
你不能这样做。不能保证列表中的相邻节点是线性布局的/内存中没有间隙。
he number is different every time
因为每个内存可能分配在不同的地址 运行。
Each node differs from one another 24 bytes
即使恰好为每个节点相邻分配内存,也可能存在打包问题。 24 字节的大小在普通的真实计算机上不太可能发生(因为该数字可以被 4 和 8 整除)。但是,如果您的尺码是23,分配的 space 将在许多架构上四舍五入。
除非您维护某种单独的计数器或索引,否则了解链表大小的唯一方法是从头到尾遍历它。
作为对 Eric 的补充,我会说:
- 据我了解,问题是指list占用的总字节数
- 一定要用
sizeof(list)
才能知道每个节点占用的字节数。我说 "sure" 是因为 sizeof(list)
的结果取决于体系结构,尤其是内存对齐和字长。
现在,如果由于任何原因禁止使用 sizeof(list)
,那么您可以通过一些计算来计算它,例如:
size_t my_sizeof_of_list()
{
struct list * zero = 0;
return (size_t) &zero[1];
}
此代码可以适用于 list
以外的类型,并且包含通用类型。
- 如果知道列表的元素个数,则总字节数为
n*sizeof(list)
(或n*my_sizeof_of_list()
)。否则,正如 Eric 指出的那样,您将需要遍历列表以计算节点数。之后,总数是n*sizeof(list)
。在最后一种情况下,更可取的是,更简单和更快,只是计算总大小而不是累加它。
find out the size of the list (without using sizeof)
sizelist = (char *)(((struct list *)0)+1)-(char *)(((struct list *)0));
或
#define sizelist ((char *)(((struct list *)0)+1)-(char *)(((struct list *)0)))
榜单:
struct list{
int Id;
short Value;
struct list *next;
};
所以我想通过使用节点的地址来找出列表的大小(不使用 sizeof)。每个节点彼此不同 24 bytes.This 是我为此目的编写的代码:
struct list *tmp;
int sum=0;
for(tmp=ptr; tmp!=NULL; tmp=tmp->next){
sum = sum + tmp->next - tmp;
}
printf("\nThe size of the list in bytes is:%d", sum);
tmp 是指向列表的指针。 ptr 是指向列表头部的指针。我使用 tmp 是因为稍后我的 code.When 需要 ptr 我执行上面的命令我得到这个:列表的大小(以字节为单位)is:143132...。每次的数字都不一样,但不是我想要的
So i want to find out the size of the list(without using sizeof) just by using the adresses of the nodes.
你不能这样做。不能保证列表中的相邻节点是线性布局的/内存中没有间隙。
he number is different every time
因为每个内存可能分配在不同的地址 运行。
Each node differs from one another 24 bytes
即使恰好为每个节点相邻分配内存,也可能存在打包问题。 24 字节的大小在普通的真实计算机上不太可能发生(因为该数字可以被 4 和 8 整除)。但是,如果您的尺码是23,分配的 space 将在许多架构上四舍五入。
除非您维护某种单独的计数器或索引,否则了解链表大小的唯一方法是从头到尾遍历它。
作为对 Eric 的补充,我会说:
- 据我了解,问题是指list占用的总字节数
- 一定要用
sizeof(list)
才能知道每个节点占用的字节数。我说 "sure" 是因为sizeof(list)
的结果取决于体系结构,尤其是内存对齐和字长。
现在,如果由于任何原因禁止使用 sizeof(list)
,那么您可以通过一些计算来计算它,例如:
size_t my_sizeof_of_list()
{
struct list * zero = 0;
return (size_t) &zero[1];
}
此代码可以适用于 list
以外的类型,并且包含通用类型。
- 如果知道列表的元素个数,则总字节数为
n*sizeof(list)
(或n*my_sizeof_of_list()
)。否则,正如 Eric 指出的那样,您将需要遍历列表以计算节点数。之后,总数是n*sizeof(list)
。在最后一种情况下,更可取的是,更简单和更快,只是计算总大小而不是累加它。
find out the size of the list (without using sizeof)
sizelist = (char *)(((struct list *)0)+1)-(char *)(((struct list *)0));
或
#define sizelist ((char *)(((struct list *)0)+1)-(char *)(((struct list *)0)))