我正在尝试使用 C 语言中的结构和指向结构的指针进行一些练习。我遇到了一个困扰我的问题。我已经设置了一个函数,该函数从指向结构的指针获取 3 个值并返回一个 float 。然而,当调用这个函数时,它修改了原始结构的值,最终导致访问冲突和一些令人讨厌的字符反流。单步执行代码后,值没问题,直到我返回函数的值。
这是我的结构:
struct product
{
int ID;
char name[MAXNAME];
char department[MAXDEPT];
float price;
int taxable;
int free_shipping_eligible;
};
typedef struct product Product;
函数原型(prototype):
Product * getInput(void);
float transactionTotal(const float price, const int taxable,
const int free_shipping);
void displayTransaction(const Product * inventory,
const float total_price);
主要内容:
int main(void)
{
// Declare a pointer to a struct.
Product * invPoint = NULL;
float grand_total = 0.0;
// Get the value of the address of a struct.
invPoint = getInput();
// Use that address to get the total of a transaction.
grand_total = transactionTotal(invPoint->price, invPoint->taxable,
invPoint->free_shipping_eligible);
// Display product information and the transaction's total.
displayTransaction(invPoint, grand_total);
return EXIT_SUCCESS;
}
这是填充结构成员值的函数:
Product * getInput(void)
{
// Declare our struct and struct pointer variables.
Product inventory;
Product * fillInventory = NULL;
// Get user input.
printf("Please enter the product's ID.\n\t");
scanf("%d", &inventory.ID);
printf("Please enter the product's name.\n\t");
scanf("%s", &inventory.name);
printf("Please enter the product's price.\n\t");
scanf("%f", &inventory.price);
printf("Which department is the product located in?\n\t");
scanf("%s", &inventory.department);
printf("Is it taxable? 0 for no, 1 for yes.\n\t");
scanf("%d", &inventory.taxable);
printf("Is it free shipping eligible? 1 for no, 0 for yes.\n\t");
scanf("%d", &inventory.free_shipping_eligible);
fillInventory = &inventory;
// Return a pointer to our struct.
return fillInventory;
}
transactionTotal 函数似乎是罪魁祸首。这是它的代码:
float transactionTotal(const float price, const int taxable,
const int free_shipping)
{
float total_price = 0.00;
float tax = (float)(taxable * TAX_RATE);
float shipping = (float)(free_shipping * SHIPPING_RATE);
total_price = price + price * tax + price * shipping;
return total_price;
}
在开始上述功能之前,我输入了以下值:
编号:232
名称:“咖啡”
部门:“食品”
价格:8.99
应税:0
free_shipping_eligible:1
transactionTotal 函数之后:
编号:-858993460
姓名:(奇怪的字符)
部门:(奇怪的字符)
价格:9.88899994
应税:-858993460
free_shipping_eligible:14679252
最佳答案
// Return a pointer to our struct.
return fillInventory;
}
你的结构对象是在你的函数中声明的,并且有一个在你的函数返回后结束的生命周期。当您的函数返回时结构对象被丢弃,之后尝试访问它会调用未定义的行为。将您的结构对象作为参数传递给函数或使用 malloc
分配其存储空间以解决您的问题。
关于c - 在 C 中,将指向结构的指针值发送到函数时返回 float 会更改结构的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34142710/