2011-11-12 51 views
0

编辑:过程结构的存储器分配

Typedef struct SPro{ 
    int arrivalTime; 
    char processName[15]; 
    int burst; 
} PRO; 

我有类型PRO

PRO Array[100]; 
PRO enteringProcess; 
//initialize entering process 

然后我需要创造一个新的过程,并用malloc然后点为该进程分配存储器的阵列从数组到malloc返回的内存块的指针。

PRO *newPro = (PRO *) malloc (sizeof(PRO)); 
newPro = enteringProcess; 
ProArray[0] = *newPro; 

看来我做错了,因为我的程序在运行时崩溃。 有什么帮助吗?谢谢!

+4

程序崩溃在哪里?在上面的代码中? PRO如何定义?对不起,但对我来说,上面的代码片段包含的信息太少。 –

+1

如何声明enterProcess?它也是一个指针吗? – Tudor

+0

即使在编辑之后我仍然很迷茫和困惑:)时间去睡觉... –

回答

1

看来你需要的指针到PRO数组:

PRO *Array[100]; 

PRO *newPro = (PRO *) malloc (sizeof(PRO)); 
/* ... */ 
Array[0] = newPro; 

我不知道enteringProcess是什么,所以我不能给意见。只是你不应该分配任何东西newPro除了返回malloc否则你会泄漏新的对象。

+0

为什么是一个指针数组?赋值Array [0] = * newPro复制变量Array [0]中newPro指向的地址的值。这项任务是正确的。 – Tudor

+0

它在语法上是正确的,但毫无意义。创建一个动态对象只是将它用作赋值的来源?如果这是您的需要,您应该使用自动(又名本地)变量。或者甚至更好,将对象直接初始化到数组中。我的猜测是,如果他使用'malloc'是因为他需要这个对象是动态的。 – rodrigo

+0

我同意,代码有点混乱。正如我在回答中所说的,我没有看到newPro指针的重点。 – Tudor

5

为什么你需要分配内存,声明

PRO Array[100]; 

已分配的内存 - 这是假设你的PRO的定义是一样的东西;

typedef struct { 
    ..... 
    } PRO; 

查看您的代码;

// Declare a new pointer, and assign malloced memory 
PRO *newPro = (PRO *) malloc (sizeof(PRO)); 

// override the newly declared pointer with something else, memory is now lost 
newPro = enteringProcess; 

// Take the content of 'enteringProcess' as assigned to the pointer, 
// and copy the content across to the memory already allocated in ProArray[0] 
ProArray[0] = *newPro; 

你可能想要这样的东西,而不是;

typedef struct { 
    ... 
    } PRO; 

    PRO *Array[100]; // Decalre an array of 100 pointers; 

    PRO *newPro = (PRO *) malloc (sizeof(PRO)); 
    *newPro = enteringProcess; // copy the content across to alloced memory 
    ProArray[0] = newpro; // Keep track of the pointers 
0

我猜enterProcess指向一个无效的地方在内存中。

newPro = enteringProcess 

是你的问题。