簡體   English   中英

為函數內部結構內的指針分配內存

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM