[英]Allocating memory for pointers inside structures in functions
假设我声明了如下结构:
typedef struct {
int *numbers;
int size; // Size of numbers once treated as array
} sstruct;
然后在main()
)中使用sstruct *example;
创建指向结构的指针(以便以后通过引用传递它) sstruct *example;
。
然后,我有一个函数,将其allocpositions()
,其中我假装为*example
包含的*p
指针分配内存位置。
如果我想将位置分配给*example
,将方向&example
传递给函数就足够了,它将以**a
形式接收它,然后执行a = (sstruct **)malloc(N*sizeof(sstruct *))
,但是我看不到如何直接在函数内部分配给*p
。
并且一旦分配,我是否仍然能够将*p
的元素作为allocpositions()
example->p[index]
allocpositions()
?
我将不胜感激!
编辑
示例代码说明了我要实现的目标:
typedef struct {
int *numbers;
int size; // size of numbers once treated as array
} ssm;
main() {
ssm *hello;
f_alloc(&hello);
}
void f_alloc(ssm **a) {
// Here I want to allocate memory for hello->p
// Then I need to access the positions of hello->p that I just allocated
}
带有注释的代码:
void f_alloc(ssm **a) {
*a = malloc(sizeof(ssm)); // Need to allocate the structure and place in into the *a - i.e. hello in main
(*a)->p = malloc(sizeof(int)); // Allocate memory for the integer pointer p (i.e. hello ->p;
}
编辑
我认为这是您所需要的:
void f_alloc(ssm **a, unsigned int length) {
*a = malloc(sizeof(ssm)); // Need to allocate the structure and place in into the *a - i.e. hello in main
(*a)->p = malloc(sizeof(int) * length); // Allocate memory for the integer pointer p (i.e. hello ->p;
(*a)->v = length; // I am assuming that this should store the length - use better variable names !!!
}
然后是一个设置/获取的功能
bool Set(ssm *s, unsigned int index, int value) {
if (index >= s->v) {
return false;
}
s->p[index] = value;
return true;
}
bool Get(ssm *s, unsigned int index, int *value) {
if (index >= s->v) {
return false;
}
*value = s->p[index];
return true;
}
我留给读者一些空余时间。
编辑2
因为我心情很好。
void Resize(ssm**a, unsigned int new_length)
{
(*a)->p = relloc((*a)->p, sizeof(int) * new_size);
(*a)->v = new_length;
}
void Free(ssm *a)
{
free(a->p);
free(a);
}
您可以使其更具容错性,以检查malloc/realloc
是否起作用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.