2016-09-16 64 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