2016-09-16 65 views
2

我遇到了一些我試圖實現的「程序流」問題。無法通過指針分配數組元素的值

下面的MWE中的輸出應該是「總和:10」,但它表示「總和:0」,因爲功能set_array_element未設置數組元素。爲什麼不呢?

#include <stdio.h> 
#include <stdlib.h> 

typedef struct example example; 
struct example { 
    int nrOf; 
    double a[]; 
}; 

void initialize_example_array(example *e); 
void set_array_element(double *el); 

example new_example(int nrOf) 
{ 
    example *e = malloc(sizeof(example) + nrOf*sizeof(double)); 
    e->nrOf = nrOf; 
    initialize_example_array(e); 
    return *e; 
} 

void initialize_example_array(example *e) 
{ 
    printf("%d\n", e->nrOf); 
    for(int i=0; i<e->nrOf; i++) 
    { 
     set_array_element(&e->a[i]); 
    } 
} 

void set_array_element(double *el) 
{ 
    *el = 1; 
} 

int main(int argc, const char * argv[]) { 
    example e = new_example(10); 

    printf("%d\n", e.nrOf); 

    int i, s=0; 
    for(i=0; i<e.nrOf; i++) 
    { 
     printf("%f\n", e.a[i]); 
     s+= e.a[i]; 
    } 
    printf("Sum: %d\n", s); 

    return 0; 
} 

回答

4

靈活的數組成員,這是結構示例的成員之一,不是一個指針。它的地址是使用結構體的地址來計算的。

具有靈活的陣列成員結構不能使用簡單的賦值操作符來分配,就像是在你的例子做:

example e = new_example(10); 

當函數返回:

return *e; 

您將有返回指針:

example* new_example(int nrOf) 
{ 
    example *e = malloc(sizeof(example) + nrOf*sizeof(double)); 
    e->nrOf = nrOf; 
    initialize_example_array(e); 
    return e; 
} 

example* e = new_example(10); 
printf("%d\n", e->nrOf); 
... 
+0

換句話說:數組不是指針!當談到陣列時,每位C老師都應該在第一句話中說清楚這一點! – Olaf