我在这里有这段代码,我认为它应该可以工作,而且确实可以!除了虽然我声明了一个指向 double 类型数组的指针,但它总是存储 int,我不知道为什么。
首先,我有这个结构,它的定义如下:
struct thing {
int part1;
double *part2;
};
然后我用struct thing *abc = malloc (sizeof(struct thing))
andpart1 = 0
和初始化这个东西part2 = malloc(sizeof(double))
。
然后,我尝试在 double 数组的特定位置设置特定值。这适用于整数,但是当我尝试 0.5 时,它将值设置为 0。当我尝试 2.9 时,它将值设置为 2。我真的不知道为什么会这样。setValue 的代码如下所示:
struct thing *setValue (struct thing *t, int pos, double set){
if (t->part1 < pos){ // check to see if array is large enough
t->part2 = realloc (t->part2, (pos+1) * sizeof(double));
for (int a = t->part1 + 1; a < pos + 1; a++)
t->part2[a] = 0;
t->part1 = pos;
}
t->part2[pos] = set; // ALWAYS stores an integer, don't know why
return t;
}
-- 编辑:所以这部分没有什么真正的恶意;但这是我的其余代码以防万一:
对我的 struct 事物进行操作的相关函数
#include "thing.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
struct thing *makeThing(){ // GOOD
struct thing *t = (struct thing *) malloc (sizeof(struct thing));
t->part1 = 0;
t->part2 = malloc (sizeof(double));
t->part2[0] = 0;
return t;
}
struct thing *setValue (struct thing *t, int pos, double set){
if (t->part1 < pos){ // check to see if array is large enough
t->part2 = realloc (t->part2, (pos+1) * sizeof(double));
for (int a = t->part1 + 1; a < pos + 1; a++)
t->part2[a] = 0;
t->part1 = pos;
}
t->part2[pos] = set; // ALWAYS stores an integer, don't know why
return t;
}
double getValue (struct thing *t, int pos){
if (pos <= t->part1){
return t->part2[pos];
}
return 0;
}
头文件:
#ifndef THING_H
#define THING_H
struct thing {
int part1;
double *part2;
};
struct thing *makeThing();
struct thing *setValue (struct thing *t, int pos, double set);
double getValue (struct thing *t, int pos);
#endif
主文件:
#include <stdio.h>
#include "thing.h"
int main (void)
{
struct thing *t = makeThing();
setValue (t, 1, -1);
setValue (t, 1, -2);
setValue (t, 10, 1);
setValue (t, 3, 1.5);
printf ("%g\n", getValue (t, 0));
printf ("%g\n", getValue (t, 1));
printf ("%g\n", getValue (t, 2));
printf ("%g\n", getValue (t, 3));
printf ("%g\n", getValue (t, 4));
printf ("%g\n", getValue (t, 5));
printf ("%g\n", getValue (t, 6));
printf ("%g\n", getValue (t, 7));
printf ("%g\n", getValue (t, 8));
printf ("%g\n", getValue (t, 9));
printf ("%g\n", getValue (t, 10));
return 0;
}
在我的电脑上,打印出来的是:0 -2 0 1 0 0 0 0 0 0 1
编辑:事实证明,当我通过代码块编译它时,它可以工作......
最终,我很困惑。