Search code examples
cpointersstructtypedefmodular

passing struct to function C


I have initialised 3 instances of a cache I have defined using typedef. I have done some processing on them in a serious of if statements in the following way :

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. 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.


Solution

  • 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.

    Pointer in C is just like the reference to object in 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. 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. In the past, this will never be the case..