c - 使用 malloc 为结构体分配内存

标签 c pointers struct malloc

我有一个名为 State 的结构:

typedef struct State{
    char alphabets[2][6]; 
    struct State *PREV; /*this points to the previous state it came from*/
    struct State *NEXT; /*this points to the next state in the linked list*/
    int cost; /*Number of moves done to get to this position*/
    int zero_index;/*this holds the index to the empty postion*/
} State;

这是我的 memAllocator() 方法:

memAllocator(){
struct State *p = (State*) malloc(sizeof(State));
if (p==NULL){
        printf("Malloc for a new position failed");
        exit(1);
}
return p;

} 这是我的主要方法。

main(){
State *start_state_pointer=memAllocator();
State start_state;
start_state.zero_index=15;
start_state.PREV = NULL;
start_state.alphabets[0][0]='C';
start_state.alphabets[0][1]='A';
start_state.alphabets[0][2]='N';
start_state.alphabets[0][3]='A';
start_state.alphabets[0][4]='M';
start_state.alphabets[0][5]='A';
start_state.alphabets[1][0]='P';
start_state.alphabets[1][1]='A';
start_state.alphabets[1][2]='N';
start_state.alphabets[1][3]='A';
start_state.alphabets[1][4]='L';
start_state.alphabets[1][5]='_';
start_state_pointer=&(start_state);
/*start_state=*start_state_pointer;*/

}

我认为语句start_state_pointer=&(start_state);只是将指针start_state_pointer分配给State start_state期间创建的少量临时空间,而不是分配给我分配的空间。 但是,当我尝试注释掉的语句 start_state=*start_state_pointer 来遵循指针并分配空间到启动状态时。它给了我一个段错误。

我刚刚开始学习 C。有人可以帮助我吗?

最佳答案

您的 memAllocatormain 函数没有显式返回类型。这种代码风格已被弃用十多年了。 C 中的函数应该始终有一个返回类型。对于 main,返回类型应为 int,对于 memAllocator 函数,返回类型应为 State *

第二个问题是,您为 State 结构分配空间,但随后填充不同 State 结构并覆盖指向该结构的指针之前使用 start_state_pointer = &(start_state); 分配的 State 结构。

要使用刚刚分配的内存,您需要使用如下内容:

State *start_state = memAllocator();
start_state->zero_index = 15;
start_state->PREV = NULL;
start_state->alphabets[0][0] = 'C';
// etc.

无需创建两个State结构。当您在原始代码中使用 State start_start; 时,您正在创建一个带有自动存储功能的结构体。这意味着该结构的空间是自动分配的,并在声明它的作用域结束时自动释放。如果您获取该结构的地址并将其传递给程序的其他部分,那么您将传递围绕指向已释放结构的指针,这可能就是您的程序崩溃的原因。

关于c - 使用 malloc 为结构体分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13897602/

相关文章:

c - 使用 writel 将 4 位写入 ioremap 内存地址

函数指针作为参数的 C++ 问题

来自不兼容指针类型的 C 指针数组赋值

c++ - 为什么我不能通过 const 指针修改变量?

c - 使用指针变量 typedef

无法将值存储在库中定义的结构上

c - 是否可以对字符数组进行位掩码

c++ - 静态常量对象

c++ - typedef struct name 没有后续结构定义的名称

c - C中的结构查找大于某个变量的元素