c - 指针被最后一个指针调用替换?

标签 c pointers

程序会打印大量营养素(碳水化合物、脂肪和蛋白质)的数量与其卡路里密度的乘积。

这部分代码一切顺利,但是,当我尝试对结果求和时,由于某种原因,代码将所有先前的指针替换为最后一个指针(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 input the name of the meal item: rice

MEAL NAME: rice

input the quantity of fat: 1

fat calories: 9

input the quantity of carbs: 12

carb calories: 48

input the quantity of protein: 3

protein calories: 12

total calories: 36

期望的结果是 9 + 48 + 12,但程序所做的是 12 + 12 + 12。

最佳答案

您正在将临时变量的地址复制到全局指针。当稍后访问指针时,这会导致未定义的行为。

由于您的函数仅返回一个值,因此您可以考虑使用函数的返回值并将总和计算为总和:

int ask_fat(void)
{
    int fat;
    printf("\ninput the quantity of fat: ");
    scanf("%d", &fat);

    fat = fat * FAT_CAL;
    printf("\nfat calories: %d\n", fat);

    return fat;
}

对其余函数执行相同的操作,然后在 main 中计算摘要,如下所示:

int main (int argc, char *argv[])
{
    ask_name();

    int sum = ask_fat() + ask_carb() + ask_prot();
    printf("total calories: %d\n", sum);
}

或者,如果您确实需要使用全局变量,则只需将它们更改为非指针并将值保存在相应的 ask_ 函数中即可。但请注意,在这种情况下全局变量不是必需的,因此最好避免使用它们。

关于c - 指针被最后一个指针调用替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46658885/

相关文章:

c - 插入二叉树时出现错误?

ios - 解析 : Compare PFObject to pointer in class

c - 两个头文件中的类型定义互换

c - Ubuntu Box 上的应用程序分析

c - 预测C代码的输出

Ruby 我们如何使用指针解冻字符串

C++在销毁引用对象后使用它

c - 在 C 中使用链表实现堆栈时出错

c - 我的代码中的段错误

c - C语言中如何分配子字符串?