【问题标题】:passing struct to function C将结构传递给函数 C
【发布时间】:2015-11-19 03:58:28
【问题描述】:

我已经初始化了 3 个使用 typedef 定义的缓存实例。我通过以下方式对它们进行了一些处理:

cache cache1;
cache cache2; 
cache cache3; 
int a;

void main(...) {
 if (a == 0) { 
 cache1.attribute = 5; 
} 
else if (a == 1) {
 cache2.attribute = 1;
}
else if (a == 2) {
cache3.attribute = 2 ;
}

但是现在我需要通过以下方式使设计模块化:

cache cache1;
cache cache2;
cache cache3;

void cache_operator( cache user_cache, int a ) {
  user_cache.attribute = a;
}

void main(...) {
  if (a == 0) {
    cache_operator(cache1,5);
}
  else if (a == 1) {
  cache_operator(cache2,1);
}
...

我无法将缓存传递给该方法。我习惯了java编程,对c指针不是很熟悉。但是,如果我如上所示传递缓存本身,我将在堆栈上传递缓存的副本,然后产生与原始代码不同的结果。在将适当的缓存传递给函数并确保正确访问它时,如何正确地将第一个设计转换为第二个设计。

【问题讨论】:

    标签: c pointers struct typedef modular


    【解决方案1】:

    在 C 语言中,如果您想跟踪原始“数据”而不是在函数中创建副本,则必须将该数据的指针传递给该函数。

    C 中的指针就像 JAVA 中对对象的引用。

    以下是你的做法。

    void cache_operator( cache *user_cache, int a ) 
    {
        user_cache->attribute = a;
    }
    

    以下是调用函数的方式。

     cache_operator(&cache1,5);
    

    我也是从 JAVA 开始的。我不知道现在为什么有些大学使用JAVA作为起始语言......这很奇怪,因为JAVA是一种将低级细节抽象的高级语言,而C是一种相当低级的语言。过去,永远不会是这样。

    【讨论】:

    • 是的,我知道,您能否演示一下在传递参数、原始函数定义和访问方法中的属性时,合成器的外观。这就是我遇到的问题。
    • 所以我会这样称呼这个函数cache_operator( * cache1, 5);?
    • 如果你觉得解决方法有效,别忘了采纳答案哦~
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 2021-03-17
    • 2013-04-12
    • 2015-01-03
    • 2012-10-06
    • 1970-01-01
    相关资源
    最近更新 更多