gpt4 book ai didi

c - 如何正确地将十进制整数添加到地址

转载 作者:行者123 更新时间:2023-11-30 18:45:53 25 4
gpt4 key购买 nike

我正在尝试将十进制整数添加到地址。 (我不太清楚地址,我猜它以十六进制工作)按以下方式:

//node_t is a structure with an int and node_t* ptr, so i have the size 8
int move = sizeof(node_t) + size; //here node_t is 8, size is 10
//so actually i want to move it by 18bytes.
node_t* tmp = (current)+sizeof(node_t) / sizeof(node_t) + size/sizeof(int)
//current is the starting address, i try to get current moving positively with 18 bytes

但事实证明,tmp 仅比 current 大 16 个字节。

我认为问题是大小被识别为十六进制,我该如何解决这个问题?

最佳答案

这没有多大意义:

node_t* tmp = (current)+sizeof(node_t) / sizeof(node_t) + size/sizeof(int)

指针算术的工作原理是添加多个元素,而不是字节。您似乎试图通过划分尺寸来解决这个问题,但这行不通。

根据表达式,我假设 current 的类型为 node_t*。添加 sizeof(node_t)/sizeof(node_t) 基本上将其移动到当前位置后面。您也可以仅使用 1 这部分。

然后添加size/sizeof(int)。这里假设元素的大小不同:int 而不是 node_t

您提到 node_t 的大小是 8。您如何将 10 除以 8? 10/8 是 1 的整数除法。这意味着您总是移动 2 个元素,即 16 个字节。

你可以尝试这个丑陋的黑客:

node_t* tmp = (node_t *)(((char*)current) + sizeof(node_t) + size);

如果您对硬件没有非常严格的对齐限制,这可以工作。

否则,您需要四舍五入到下一个对齐良好的地址。

关于c - 如何正确地将十进制整数添加到地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53434427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com