First User
First User

Reputation: 771

C: pointer arithmetic not working when done through a function call?

I have a dynamically allocated "matrix", allocated like so:

int **m = (int **) malloc (sizeof (int *) * rows);
for (i = 0; i < rows; i++)
    m[i] = (int *) malloc (sizeof (int) * cols);

I would like to "truncate" this matrix, by that I mean suppose I had something like this:

1 2 3
4 5 6
7 8 9

, truncating it by 1 row would give me :

4 5 6
7 8 9

I can do this quite easily by

m++;
rows--;

which produces the desired result, however if I were to move the above two statements into a function like so:

void truncate (int **m, size_t *rows)
{
   m = m + 1;
   *rows = *rows - 1;
}

it doesn't work as expected. The following call

truncate (m, &rows);

produces

1 2 3
4 5 6

What could I be doing wrong ? The reason I want to do this is to generalize this and allow any number of rows to be truncated, so I could add a third parameter and increment m and decrement *rows by that number.

Upvotes: 0

Views: 28

Answers (1)

Aldan Creo
Aldan Creo

Reputation: 854

Inside of truncate, you have to increment the value of the original m. That means passing m by reference, not by value. Therefore, you have to use int ***m:

void truncate (int ***m, size_t *rows)
{
   (*m)++;
   (*rows)--;
}

Upvotes: 1

Related Questions