2

ここにこのコードがあり、うまくいくと思います。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

編集:コードブロックを介してコンパイルすると、動作することがわかりました...

結局、私は混乱しています。

4

2 に答える 2

1

DoubleはCでintに変換しますか?

いいえ、そうではありません。doubleタイプのオブジェクトに値を代入するdoubleと、変換はまったく行われません。

あなたの問題は、あなたが示したコードにはありません。それは別の場所にあります(印刷方法、愚かな#define、その他のもの)。

おー!そして、本当にrealloc()s が機能することを確認する必要があります。そうしないと、エラーではなく、ユーザーがわずかに誤った値を取得する可能性があります...

コメントで述べたように、コードは ideone で期待どおりに機能します。

于 2012-11-18T15:38:19.910 に答える