Home > Enterprise >  Create function using pointers (very new to coding)
Create function using pointers (very new to coding)

Time:06-01

The question in my book is: The function:

void int_concat (int * i1, const int * i2, unsigned int n, unsigned int pos);

concatenates a field with n integers from i2 to position "pos" in the field i1. Implement the int_concat function using pointers, you may not use indexing. Your solution must also not use any standard function.

one answer is:

void int_concat (int *i1, const int *i2, unsigned int n, unsigned int pos)
{
 int *insert = i1   pos;
 while ( n-- )
 {
 *insert   = *i2  ;
 }
}

I can not seem to understand they have a *insert = *i2 ;. The only thing I think I understand is that int *insert = i1 pos; creates the address where the n integers are placed. Can someone explain..

CodePudding user response:

So here is how the code works!

As you said int *insert = i1 pos; is the address in the array i1 where the numbers will be added from i2.

Now for the while, it will simply loop until n = 0, and the way they have write it is equivalent to this:

    while(n>0)
    {
        n-=1;
        //Do smth
    }

Now for the actual

*insert   = *i2  ;

So what happens here is you take reference to the value that is at position insert, and you make it equal i2. After that you increment both pointers, therefore this line can be write out as:

*insert = *i2;
insert  ;
i2  ;

Here is the whole code written in a more comprehensive manner

    void int_concat(int *i1, const int *i2, unsigned int n, unsigned int pos)
    {
        // This is the fixed position
        int *insert = i1   pos;
        while(n>0)
        {
            n-=1;
            *insert = *i2;
            insert  ;
            i2  ;
        }
    }

Now if you are still struggling let me do an example application:

Say here is i1 = [1,2,3]

And here is i2 = [4,5,6]

Let's say pos is 1, and n = 2;

So the code will change the i1 to : [1,4,5] because the value a pos = 1 in i2 is equal to 4. But since n = 2 it will increment the position of the insert and i2 And so the value 5 will be place in i1.

  •  Tags:  
  • c
  • Related