0

I'm allocating memory for a 2d array dynamically using the below code,

int **matrix = (int **) malloc(testVals[m].rows*sizeof(int));
for(int i = 0 ; i < testVals[m].rows ; i++)
    matrix[i] = (int *) malloc(testVals[m].columns*sizeof(int));

but I'm in need to add extra rows and columns as per requirements. I'm able to add extra rows like this, where i'm converting the matrix to square matrix

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

but how to do that for adding columns?

2
  • how is textVals declared? Commented Apr 21, 2014 at 2:14
  • those are accessing the structure.. its just the number of rows and columns Commented Apr 21, 2014 at 2:15

1 Answer 1

0

You can use realloc on each row if you need to add a column: That is, if you need to add N columns, you realloc each row by extending each of them by N.

EDIT: You can look at this possible duplicate

Sign up to request clarification or add additional context in comments.

2 Comments

the values stored before will sustain?
Yes (read my link above on realloc). Values are preserved, only extra memory is allocated. Does that answer your question ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.