【问题标题】:C - iterating numberOfProducts variable does not workC - 迭代 numberOfProducts 变量不起作用
【发布时间】:2020-10-19 00:13:35
【问题描述】:

我是 C 的新手,我正在创建一个在线商店来管理其库存中的一堆产品。我在打印所有产品时遇到问题。当用户输入 '1' 应该遍历 productCollection 中的所有元素并打印出每个 Product 对象时,它什么也不打印。

我认为这是因为 numberOfProducts 始终为 0,即使我在 addProduct() 中对其进行了迭代。尽管我将迭代器放在哪里,但当我打印 numberOfProducts 时,它总是打印 0。我想知道为什么?

main.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "defs.h"

void printInventory(ProductCollectionType*);
int addProduct(ProductCollectionType*, int, char*, int, float);

int main(){


    InventoryType store;
    store.storeName = "Walmart";
    
    ProductCollectionType p;
    p.numberOfProducts = 0;
    
    addProduct(&p, 1001, "Grape juice", 20, 12.5);
    addProduct(&p, 1002, "Apple juice", 30, 4.3);
    
    
    int choice;
    printf("(1) Print inventory \n");

    printf("\n");
    printf("Enter choice: ");
    scanf("%d", &choice);
  
    printf("%d \n", p.numberOfProducts);
  
    if(choice == 1){
        printInventory(&p);
    } 
    
    return 0;


}

【问题讨论】:

  • addProduct 中,for(i = 0; i &lt; productCollection-&gt;numberOfProducts; ++i) 不正确。当然,那个循环永远不会运行。 productCollection-&gt;numberOfProducts 从 0 开始,并且永远不能递增,因为循环永远不会运行。你不需要任何循环。直接跳转到你要添加的索引即可。确保它不会溢出数组。
  • 编译时,始终启用警告,然后修复这些警告。 (对于gcc,至少使用:-Wall -Wextra -Wconversion -pedantic -std=gnu11)注意:其他编译器使用不同的选项来产生相同的结果。函数:addProduct() 导致消息:untitled1.c:79:1: warning: control reaches end of non-void function [-Wreturn-type] 这不是唯一的问题!

标签: arrays c pointers struct


【解决方案1】:

在C语言中,函数参数是按值传递的。

int addProduct(ProductCollectionType productCollection

在此函数中,productCollection 是调用方结构的副本

productCollection.numberOfProducts++;

所以该行修改了一个局部变量,而不是调用者的变量。

要修复,请传入一个 insted 指针。

int addProduct(ProductCollectionType *productCollection, int i, char* n, int u, float p)
{
    ...
    productCollection->numberOfProducts++;
}

并调用为:

addProduct(&p, 1001, "Grape juice", 20, 12.5);

【讨论】:

  • 嗨!所以我做了以下更改,但由于某种原因 numberOfProducts 仍然打印为 0?
  • 您需要在任何地方进行相同的更改 - 包括 printInventory 函数。
  • 我在帖子中更新了我的代码以包含我现在的代码。我为每个函数添加了一个 * 并使用箭头来访问它,但问题仍然存在。我的代码中是否有可能遗漏了其他内容?
猜你喜欢
  • 1970-01-01
  • 2017-11-12
  • 1970-01-01
  • 2020-11-23
  • 2014-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多