How to implement the dup function for a variable in C

advertisements

I have this:

void duplication(int **tab1, int **tab2, int n, int m)

The goal is to copy tab1 into tab2, so i will get the same two tables.

How can i do this, because i know that using tab2 = tab1 is not working in my case :)

Sorry if it's a stupid question, i'm actually learning C!

Thank you.


assuming n and m are the dimensions, and you know which one applies to which dimension, you need a double loop something like this:

for ( int x = 0; x < n; ++x )
{
    for ( int y = 0; y < m; ++y )
    {
        tab2[x][y] = tab1[x][y];
    }
}

Thats a couple of big assumptions I am making given the documentation of the function you provide, but hopefully the code gives you an idea of what needs to be done, and you can substitute the correct variables in the correct places.

For further reference, the term associated with this kind of data copying is what is called a "Deep copy". When dealing with pointers, copying the pointer value is typically insufficient, and frequently unsafe. If you would like more references on this type of code, search around for "Deep copy"