C中的进程结构内存分配

Glo*_*ove 0 c arrays malloc structure

编辑:

Typedef struct SPro{
     int arrivalTime;
     char processName[15];
     int burst;
} PRO;
Run Code Online (Sandbox Code Playgroud)

我有一个PRO类型的数组

PRO Array[100];
PRO enteringProcess;
//initialize entering process
Run Code Online (Sandbox Code Playgroud)

然后我需要创建一个新进程并使用malloc为该进程分配内存然后将指针从数组指向malloc返回的内存块.

PRO *newPro = (PRO *) malloc (sizeof(PRO));
newPro = enteringProcess;
ProArray[0] = *newPro;
Run Code Online (Sandbox Code Playgroud)

由于程序在运行时崩溃,我似乎做错了.有帮助吗?谢谢!

Sor*_*ren 5

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

  PRO Array[100];
Run Code Online (Sandbox Code Playgroud)

已经分配了内存 - 假设你的PRO定义是这样的;

  typedef struct {
     .....
  } PRO;
Run Code Online (Sandbox Code Playgroud)

检查您的代码;

// 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;
Run Code Online (Sandbox Code Playgroud)

你可能想要这样的东西;

  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
Run Code Online (Sandbox Code Playgroud)