c - 将结构传递给函数 C

标签 c pointers struct typedef modular

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

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

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

以下是您的操作方式。

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

以下是调用函数的方式。

 cache_operator(&cache1,5);

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

关于c - 将结构传递给函数 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33795010/

相关文章:

c - 如何在 Code::Blocks 中添加另一个 C 文件

c++ - 指向C++中的指针的指针

swift - 在 Swift 中制作结构字典时必须导入 Foundation 吗?

在 C 中从 char * 转换为 char[31]

C : Acessing a structure within a structure

谁能解释一下 switch、while 和 continue 的相互作用吗?

c++ - 在 C++ 程序中使用 Cheat Engine 基地址

c++ - 基本的 C 风格字符串复制

c - 将数组结构传递给函数

c - 读取命令行参数