gpt4 book ai didi

c - 在不使用 malloc 的情况下将固定大小的对象分配给指针(指向结构)

转载 作者:太空宇宙 更新时间:2023-11-04 06:08:09 26 4
gpt4 key购买 nike

我有一个指向结构 list* ptr 的指针该结构包含一个 char 和一个指向下一个结构的指针,它们用于结构数组,如下所示:

list array[setSize]; //setSize is defined as 20 

在不使用 malloc 的情况下,我需要初始化 list* ptr 以便它拥有数组的所有元素。

我尝试了以下方法,但出现段错误。我相信我完全误解了指针的工作原理。 (好久没接触C了)

int j = 0;
ptr = sizeof(array[j]); //i was thinking this would allocate space
for(j; j < setSize; j++)
array[j].next = array[j+1].next;
ptr = array; //i thought this would point to the beginning of the array

我看过很多关于 C 和链表的网站。我有书,但它们没有提供足够的细节来说明指针或结构的这种特殊用途。我已经尝试了一段时间,但我确信我遗漏了一些东西。

我只需要了解我哪里出了问题以及应该朝哪个方向前进。

感谢所有帮助。

以下是包含更多代码的重新发布:

//this should initialize array so that ptr contains all array elements
void initialize ( list array[] ) {
int j;
for(j = 0; j < setSize - 1; j++){
array[j].next = array[j+1].next; //using the & does not seem to work, so I don't use it
array[j].next = NULL;
}
ptr = &(array[0]);
}

稍后我在我自己的 malloc 函数中使用它(这是发生段错误的地方)

//this should allocate a new list cell in array
list* my_malloc () {
list* temp;
temp = ptr;
if(ptr = 0) {printf("Empty!\n"); return;}
else{ //the next line creates the seg fault
ptr = (*ptr).next;
}
return temp;
}

list* cell ( char n, list* next ) {
list* x = my_malloc();
x->value = n;
return x;
x->next = next;
return x;
}

main ( void* argv, int argc ) {
initialize(array);
list* x = nil;
char ch = a;
int i;
for ( i = 0; i < setSize; i++ )
x = cell(ch,x);
for ( i = 0; i < 10; i++ ) {
list* y = x->next;
my_free(x); //this is my own free function
x = y;
};
for ( i = 0; i < 10; i++ )
x = cell(ch,x);
}

最佳答案

除了这一行,你所拥有的一切都非常接近意义:

ptr = sizeOf(buffer[j]);

我猜你指的是 sizeof 吗?无论如何,该操作是没有意义的(并且是非法的,因为您试图将整数分配给指针类型的变量)。您不需要分配任何内存,array 的定义已经完成了。

您的 for 循环确实有问题 - 您将越过数组末尾,这可能是导致段错误的原因。要么是那个,要么是您没有初始化 j,所以它可能访问了一些它不应该访问的内存。我想你可能想要这样的东西:

for (j = 0; j < setSize - 1; j++) 
{
array[j].next = &array[j+1];
}

编辑:你的段错误的原因是这一行:

if(ptr = 0) {printf("Empty!\n");  return;}

设置 ptr0。我想你想要一个 == 在那里。还有一点 - 你说“使用 & 似乎不起作用,所以我不使用它”。这可能意味着您的 list 结构声明不正确,或者至少是以非常不标准的方式声明的。您可能应该展示更多您的程序 - 看起来您对指针的工作方式有一些非常基本的误解。

关于c - 在不使用 malloc 的情况下将固定大小的对象分配给指针(指向结构),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5625144/

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