在C中将double *转换为double [9]

时间:2014-05-20 13:40:26

标签: c pointers double

如果doulble *只指向一个double但不指向数组,我可以转换它。

这是我的功能,

double fun(double * in){
  return *in;
}

我的double * in有9个元素,我正在尝试将它们传递给数组out[9];

2 个答案:

答案 0 :(得分:-1)

您无法返回数组,您需要在函数外声明它:

void fun(double *out, double *in, size_t num_items){
  int i;
  for (i = 0; i < num_items; i++) {
    out[i] = in[i];
  }
}

// Somewhere else in your code:
double destination[9];
fun(destination, in, 9); // Copy 9 doubles into destination

答案 1 :(得分:-1)

#include <stdio.h>
#include <string.h>

typedef struct dbl9 {
    double array[9];
} Dbl9;

Dbl9 fun(double *in){
    Dbl9 ret;
    memcpy(ret.array, in, sizeof(ret.array));//There can be no assurance that <in> the correct
    return ret;
}

int main(){
    double array[9] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0};
    Dbl9 dbl9= fun(array);
    int i;
    for(i=0;i<9;++i){
        printf("%f\n", dbl9.array[i]);
    }
    return 0;
}