何が起こるかは、多量栄養素(炭水化物、脂肪およびタンパク質)の量をカロリー密度で乗算することです。ポインターは最後のポインター呼び出しで置き換えられますか?
しかし、私は結果を合計しようとすると、コードは何らかの理由で代わりに前のすべてのポインタを最後のポインタ(prot_ptr)で置き換えます。
これはソースコードである:
#include <stdio.h>
#include <stdlib.h>
#define CARB_CAL 4
#define PROT_CAL 4
#define FAT_CAL 9
int *fat_ptr;
int *prot_ptr;
int *carb_ptr;
void ask_name(void);
void ask_fat(void);
void ask_carb(void);
void ask_prot(void);
// main function
int main (int argc, char *argv[])
{
// food name
ask_name();
ask_fat();
ask_carb();
ask_prot();
int sum = *fat_ptr + *carb_ptr + *prot_ptr;
printf("total calories: %d\n", sum);
}
void ask_name(void)
{
char *name;
printf("input the name of the meal item: ");
name = malloc(6 * sizeof(char));
scanf("%s", name);
printf("\nMEAL NAME: %s\n", name);
free(name);
}
// fats
void ask_fat(void)
{
int fat;
printf("\ninput the quantity of fat: ");
scanf("%d", &fat);
printf("\n");
printf("fat calories: %d\n", (fat * FAT_CAL));
int int_fat = (fat * FAT_CAL);
fat_ptr = &int_fat;
}
// carbs
void ask_carb(void)
{
int carb;
printf("\ninput the quantity of carbs: ");
scanf("%d", &carb);
printf("\n");
printf("carb calories: %d\n", (carb * CARB_CAL));
int int_carb = (carb * CARB_CAL);
carb_ptr = &int_carb;
}
// proteins
void ask_prot(void)
{
int prot;
printf("\ninput the quantity of protein: ");
scanf("%d", &prot);
printf("\n");
printf("protein calories: %d\n", (prot * PROT_CAL));
int int_prot = (prot * PROT_CAL);
prot_ptr = &int_prot;
}
、これは出力例である:
./learn入力食アイテムの名称:米
MEAL名:米
入力脂肪量:1
脂肪カロリー:9
入力炭水化物の量:12
炭水化物のカロリー:48
入力タンパク質の量:3個の
タンパク質カロリー:12個の
総カロリー。 36
所望の結果は、合計9 + 48 +12のようになりますが、プログラムの機能は12 + 12 + 12の合計です。
一時変数のアドレスが返されないため、未定義の動作が発生します。グローバル変数をポインタ以外のものにすると、コードが正常に動作するはずです。 – vasek