ここにこのコードがあり、うまくいくと思います。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;
}
-- 編集: したがって、この部分には特に悪意はありません。しかし、これが私のコードの残りの部分です。
私の構造体で動作する関連関数
#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
編集:コードブロックを介してコンパイルすると、動作することがわかりました...
結局、私は混乱しています。