I want to add a row and a column of 1 around an multidimensional array in C.
For the input 1,2,3,4,5,6,7,8,9 - this is how I want it to be added. Is there in C a function like append in python, or how this can be done?
The code I already have for asking the user for elements and printing:
#include <stdio.h>
int main()
{
int n,m;
printf("Lines: ");
scanf("%d" , &n);
printf("Columns: ");
scanf("%d", &m);
int arr[n][m];
// Input Elements
printf("Input array elements: \n");
for (int i=0 ; i<n ; i )
{
for(int j=0 ; j<m ; j )
{
printf("arr[%d][%d]=",i,j);
scanf("%d" , &arr[i][j]);
}
}
// Show Elements
for (int i=0 ; i<n 1 ; i ) {
for(int j=0; j<m 1; j ) {
printf("%d\t", arr[i][j]);
}
printf ("\n");
}
return 0;
}
Thanks
CodePudding user response:
The size of array does not change during its lifetime. Even though you use Variable-Length Array, word "variable" mean that the size is kept in a variable, not that the size itself is variable.
Therefore you must create a new padded array and fill it:
// add 2 to each dimension due to 1-element-wide strips on each side
int padded[n 2][m 2];
// copy data from the old array
for (int i = 0; i < n; i)
for (int j = 0; j < m; j)
padded[i 1][j 1] = arr[i][j];
// fill padded area
for (int j = 0; j < m 2; j)
padded[j][0] = padded[j][m 1] = 1;
for (int i = 0; i < n 2; i)
padded[0][i] = padded[n 1][i] = 1;
This code can be easily moved to a bit more generic helper function that uses VLA parameters:
void pad_matrix(int n, int m,
int pad_size, int pad_val,
int src[n][m],
int dst[n 2 * pad_size][m 2 * pad_size]) {
for (int i = 0; i < n 2 * pad_size; i) {
for (int j = 0; j < m 2 * pad_size; j) {
// position in src
int ii = i - pad_size;
int jj = j - pad_size;
if (0 <= ii && ii < n && 0 <= jj && jj < m)
dst[i][j] = src[ii][jj];
else
dst[i][j] = pad_val;
}}
}
Usage could be:
int padded[n 2][m 2];
pad_matrix(n, m, 1, 1, arr, padded);