[英]memory allocation in C for pointers
I'm trying to build a structure called PROCESS in C, this struct should contain the ID(id) and waiting time (wt) of the process. 我正在尝试在C中构建一个称为PROCESS的结构,该结构应包含该进程的ID(id)和等待时间(wt)。
typedef struct PROC{
int id;
int wt;
}PROCESS;
PROCESS *pt = NULL;
Now I want to make more then one instance of this struct like an array. 现在,我要制作此结构的一个以上实例,如数组。 what I want to do is something like this':
我想做的是这样的:
PROCESS pt[10];
pt[0].id = 5;
pt[1].id = 7;
But I want to do it using dynamic memory allocation: 但是我想使用动态内存分配来做到这一点:
pt = calloc(2,sizeof(PROCESS));
pt[0]->id = 5;
What is my mistake? 我怎么了
pt
is a pointer to PROCESS
, pt[0]
is the first PROCESS
object pointed to by pt
. pt
是一个指向PROCESS
, pt[0]
是第一PROCESS
对象通过指向pt
。 The ->
operator to access members of a struct must be used with pointers only, otherwise use .
用于访问结构成员的
->
运算符必须仅与指针一起使用,否则使用.
pt[0].id = 5;
would be correct. 是正确的。 1
1个
An since you say you are doing C, you don't need to cast malloc
or calloc
. An因为您说您正在执行C, 所以不需要
calloc
转换malloc
或calloc
。
PROCESS *pt = calloc(2, sizeof *pt);
if(pt == NULL)
{
// errror handling
// do not continue
}
pt[0].id = 5;
pt[1].id = 7;
Also don't forget to check the return value of calloc
and don't forget to free the memory later with free(pt);
同样不要忘记检查
calloc
的返回值,也不要忘记稍后使用free(pt);
释放内存free(pt);
. 。
Fotenotes 脚注
1 Note that this would be equivalent to 1请注意,这等同于
pt->id = 5;
but if you want to set id
of the second element, you would need to do 但是如果您要设置第二个元素的
id
,则需要
(pt+1)->id = 7;
but I think it's more readable to do 但我认为这样做更具可读性
pt[1].id = 7;
typedef struct process{
int id;
int wt;
}processes;
I would allocate like this-> 我会这样分配->
int numberOfDynamicStructs=2;
processes* myProcesses= calloc(numberOfDynamicStructs,sizeof(processes));
Write-> 写->
myProcesses[0].id=1;
myProcesses[1].id=2;
Read-> 阅读->
printf("%d %d",myProcesses[0].id,myProcesses[1].id);
Free when done.. 完成后免费。
/A /一种
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.