如何在C中将struct中的数组更改为指针

时间:2018-06-12 20:48:19

标签: c

我有结果和我的功能:

#define MAX 4096
typedef struct{
   char comment[40];
   int nbpts;
   float time[4096];
   float value[4096];
} trace;
void simuTrace(int tmax, float dt, float params[], trace* uneTrace){
    int i = 0;
    float v = 0, w = 0, dv = 0, dw = 0, t = 0;
    while (t<tmax && i < MAX){
        dv = (params[0]-v)*(v-1)*v - w;
        dw = params[4]*(params[1]*v-params[2]*w-params[3]);
        v += dv*dt;
        w += dw*dt;
        uneTrace->time[i] = t;
        uneTrace->value[i] = v;
        i++;
        t += dt;
    }
    uneTrace->nbpts = i+1;
    uneTrace->comment[40]= "CommentaireDeLaTrace";
}

我想在这里更改结构,它不限制MAX,但我不知道如何制作。如何通过新结构&gt;

更改函数中的某些值
typedef struct{
    char comment[40];
    int nbpts;
    float *time;
    float *value;
} trace;

1 个答案:

答案 0 :(得分:2)

使用malloc

typedef struct{
    char comment[40];
    int nbpts;
    float *time;
    float *value;
} trace;

void simuTrace(int tmax, float dt, float params[], trace* uneTrace){
    int i = 0;
    float v = 0, w = 0, dv = 0, dw = 0, t = 0;
    int count = tmax/dt;
    uneTrace->time = malloc(count * sizeof(float));
    uneTrace->value = malloc(count * sizeof(float));
    while (i < count){
        dv = (params[0]-v)*(v-1)*v - w;
        dw = params[4]*(params[1]*v-params[2]*w-params[3]);
        v += dv*dt;
        w += dw*dt;
        uneTrace->time[i] = t;
        uneTrace->value[i] = v;
        i++;
        t += dt;
    }
    uneTrace->nbpts = i+1;
    strcpy(uneTrace->comment, "CommentaireDeLaTrace");
}