【问题标题】:allocating memory to a struct using malloc使用 malloc 为结构分配内存
【发布时间】:2012-12-16 00:50:05
【问题描述】:

我有一个名为 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。有人可以帮我解决这个问题吗?

【问题讨论】:

  • 你想做什么?这行 start_state_pointer=&(start_state); 丢弃了指向已分配内存的唯一指针,永远丢失了它。
  • 我试图编译你的代码并得到大量错误:codepad.org/RFQi7oHH/raw.txt
  • 我基本上是在尝试用状态填充我创建的内存。即我想将 start_state 及其所有包含复制到新分配的内存中。

标签: c pointers struct malloc


【解决方案1】:

您的 memAllocatormain 函数没有明确的返回类型。这种代码风格已经被弃用了 10 多年。 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; 时,您正在创建一个具有称为自动存储 的结构。这意味着该结构的空间是自动分配的,并在声明它的范围结束时自动为您释放。如果您获取该结构的地址并将其传递给程序的其他部分,那么您将传递围绕指向已释放结构的指针,这可能是您的程序崩溃的原因。

【讨论】:

    猜你喜欢
    • 2015-11-09
    • 2015-06-27
    • 2015-01-05
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-30
    • 1970-01-01
    相关资源
    最近更新 更多