gpt4 book ai didi

c - 使用具有双指针的结构及其内存构成

转载 作者:行者123 更新时间:2023-12-03 22:54:48 25 4
gpt4 key购买 nike

我制作了这段代码,我在其中为一个结构分配然后释放内存:

struct item {
int val;
int *vectOfInt;
struct item *next;
};

void relItem(struct item **currItem) {
struct item *temp;
int *intTemp;

temp = *currItem;
intTemp = (*currItem)->vectOfInt;
*currItem = (*currItem)->next;
free(temp);
free(intTemp);
}

int main() {
int array[] = {0, 1, 2, 3, 4, 5};
struct item *list = NULL;

list = (struct item*) malloc(sizeof(struct item));
list->val = 0;
list->vectOfInt = array;
list->next = NULL;

relItem(&list);

return 0;
}

编辑:评论代码:

struct item {
int val;
struct item *next;
};

void edit(struct item *currItem) {
currItem->val = 2;
}

int main() {
struct item *list = NULL;
list = (struct item*) malloc(sizeof(struct item));
list->val = 0;
list->next = NULL;

edit(list);

//list-val == 2

return 0;
}
  • 如何在不使用指向结构的双指针的情况下做同样的事情?

  • 你能解释一下为什么以及它是如何工作的吗(指针和双指针)?

  • 我不明白结构在主内存中是如何表示的(例如 int a[5];在内存中,a 是指向分配给 a[5] 数组的缓冲区的第一个位置的指针)

用 ha 指针初始化的结构的相等表示是什么(结构项 *s) ?

最佳答案

-您需要使用双指针,因为您需要更改指向您的结构的指针,并且在 C 中不允许通过引用调用。

- 它不适用于单个指针。因为您想更改指向对象的指针。您可以通过语句 *currItem = (*currItem)->next;为了永久更改它,您需要使用指向它的指针。这让你使用双指针。

这样想:

你有一个整型变量a,你希望一个函数改变它的值。您只需使用指向变量 a 的指针调用此函数喜欢:

void changeTheValue(int *x)
{
*x = 7;
}
void main()
{
int a = 5;
changeTheValue(&a);
}

在你的情况下,你想改变你的指针的值,你只需将它的指针传递给函数。(双指针)就那么简单。 如果你想用函数改变某物的值,那么你必须将它的指针传递给函数。

-当您调用 malloc 时,您需要从中获取空间。并且您声明您想要一个与结构大小一样大的空间。 (就像你在这里做的那样 list = (struct item*) malloc(sizeof(struct item));)并且 malloc 分配了一个和你的结构一样大的空间。如果你的结构的大小是 1 个字节,那么你有 1 个字节的空间,如果它是 4,那么你有连续的 4 个字节。看,这就是您的结构保存在内存中的方式。如果您声明一个结构变量或数组等,那么您的结构将像数组一样保存在内存中(不知道是否是一个很好的比喻)。第一个成员先来,然后是第二个......

假设你有一个结构

struct myStruct
{
int a;
float b;
char c;
};

然后内存看起来像


一个


b


c

ps:您正在 free(intTemp); 行上非法调用 free 您正在 *free*ing 一个您没有*malloc*ed 的变量。

关于c - 使用具有双指针的结构及其内存构成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6843295/

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