简体   繁体   English

将struct传递给函数C

[英]passing struct to function C

I have initialised 3 instances of a cache I have defined using typedef. 我已经初始化了3个使用typedef定义的缓存实例。 I have done some processing on them in a serious of if statements in the following way : 我以下列方式对它们进行了一些认真的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 ;
}

However now I need to make the design modular in the following way: 但是,现在我需要通过以下方式使设计模块化:

 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); } ... 

I am having trouble with passing the cache to the method. 我在将缓存传递给方法时遇到麻烦。 I'm used to java programming and I'm not very familiar with c pointers. 我习惯了Java编程,对c指针不是很熟悉。 However, if I pass the cache itself as shown above I am passing a copy of the cache on the stack which then produces results different to the original code. 但是,如果如上所述传递高速缓存本身,则会在堆栈上传递高速缓存的副本,从而产生与原始代码不同的结果。 How do I properly transform the first design into the second design when it comes to passing the appropriate cache to the function and making sure it is accessed properly. 在将适当的缓存传递给函数并确保正确访问该函数时,如何将第一个设计正确转换为第二个设计。

In C language, if you want to keep track of the original 'data' instead of creating a copy in the function, you have to pass the pointer of that data to that function. 在C语言中,如果要跟踪原始“数据”而不是在函数中创建副本,则必须将该数据的指针传递给该函数。

Pointer in C is just like the reference to object in JAVA. C中的指针就像对JAVA中对象的引用一样。

Following is how you do it. 以下是您的操作方法。

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

Following is how you call the function. 以下是如何调用该函数。

 cache_operator(&cache1,5);

I also started with JAVA. 我也从JAVA开始。 I don't know why some universities nowadays use JAVA as beginning language... It is quite strange, since JAVA is a high-level language making the abstraction of low-level detail, whereas C is a rather low-level language. 我不知道为什么现在有些大学将JAVA用作开始语言...这很奇怪,因为JAVA是一种高级语言,抽象了低级细节,而C是一种相当低级的语言。 In the past, this will never be the case.. 在过去,情况永远不会如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM