2011-11-12 52 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 

是你的問題。