2015-06-07 48 views
1

比方說,我聲明結構,因爲它遵循:分配內存的指針,內部結構,功能

typedef struct { 
    int *numbers; 
    int size; // Size of numbers once treated as array 
} sstruct; 

我在main()創建一個指向結構(爲了通過參考隨後通過它)使用sstruct *example;

然後我有一個函數,稱之爲allocpositions(),其中我假裝爲*example中包含的*p指針分配內存位置。

如果我想給位置分配給*example,這將是足夠多的方向&example傳遞給函數,那會接受它作爲**a,然後像做a = (sstruct **)malloc(N*sizeof(sstruct *)),但我不知道怎樣才能分配直接到*p裏面的函數。

而且一旦分配,我仍然可以參考*p中的元素作爲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 
} 
+1

我沒有得到你想要達到的目標。你可以重新解釋一下你的問題嗎?你到目前爲止嘗試過什麼?請向我們展示更多代碼。 – ckruczek

+0

給出功能代碼,它太複雜了,難以理解 – Subinoy

+0

只是增加了一個更具說明性的例子。 –

回答

2

代碼註釋:

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; 
} 

我離開做自由位讀者。

EDIT 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工作過

+0

從現在開始,我可以用'hello-> p [index]'來引用'p'的元素,還是應該是'hello [0] - > p [index]'? –

+0

第一段代碼(一旦編輯完成)對我來說很好,謝謝!你能否提供一些解釋,說明爲什麼需要函數Get()和Set()?我之前沒有使用布爾函數,甚至我明白他們在做什麼,我不明白爲什麼他們需要。 –

+0

@AlexanderGeorge - 因爲他們檢查索引是否在限制範圍內,並且使開發人員能夠在他們不是 –