pass matrix by reference and scan values - c

I'm trying to scan values into a matrix that is passed by reference to a function and that's not compiled.
What's wrong?
I think the problem is in line of scanf but I don't know how to fix it.
#include <stdio.h>
#include <stdlib.h>
int** initMatrix(int lines, int columns) {
int i;
int** matrix;
matrix = (int**) calloc(lines, sizeof(int*));
for (i = 0; i < lines; i++) {
matrix[i] = (int*) calloc(columns, sizeof(int));
}
return matrix;
}
void fillMatrixValues(int*** matrixA, int lines, int columns) {
int i, j;
for (i = 0; i < lines; i++) {
for (j = 0; j < columns; j++) {
scanf("%d", matrixA[i][j]);
}
}
}
void printMatrix(int** matrix, int lines, int columns) {
int i, j;
for (i = 0; i < lines; i++) {
for (j = 0; j < columns; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}
void main() {
int** matrixA;
int lines = 2, columns = 2;
matrixA = initMatrix(lines, columns);
fillMatrixValues(&matrixA, lines, columns);
printMatrix(matrixA, lines, columns);
}

void main -> undefined behaviour
Use
int main(void)
or
int main(int argc, char ** argv)
You should check return value of scanf
if (scanf("%d", matrixA[i][j]) != 1)
{
// failed
}
Next problem
void fillMatrixValues(int ***matrixA, int lines, int columns)
fillMatrixValues(&matrixA, lines, columns)
to
void fillMatrixValues(int **matrixA, int lines, int columns)
fillMatrixValues(matrixA, lines, columns)

Related

Function inputElements() taking input only once

I am trying to create a program to find the transpose of a matrix my dynamic memory allocation. However, while entering the elements of the matrix I can't input more than one element, its only taking the a[0][0] as the input and the program is ending after that.
#include <stdio.h>
#include <stdlib.h>
void createMatrix(int **, int, int);
void inputElements(int **, int, int);
void transpose(int **, int **, int, int);
void display(int **, int, int);
void main()
{
int **matrix, **trans, rows, cols;
printf("\nEnter number of rows in the matrix: ");
scanf("%d", &rows);
printf("\nEnter number of columns in the matrix: ");
scanf("%d", &cols);
createMatrix(matrix, rows, cols);
createMatrix(trans, cols, rows);
inputElements(matrix, rows, cols);
transpose(matrix, trans, rows, cols);
printf("\nMATRIX:\n");
display(matrix, rows, cols);
printf("\nTRANSPOSE OF THE MATRIX:\n");
display(trans, rows, cols);
}
void createMatrix(int **a, int r, int c) //for allocating memory for the matrix
{
int i, j;
a = (int **)malloc(sizeof(int *) * r);
for(i = 0; i < r; i++)
a[i] = (int *)malloc(sizeof(int) * c);
}
void inputElements(int **a, int r, int c) //for entering matrix elements
{
int i, j, t;
for(i = 0; i < r; i++)
{
for(j = 0; j < c; j++)
{
printf("\nEnter matrix element[%d][%d]: ", i + 1, j + 1);
fflush(stdin);
getchar();
scanf("%d", &(a[i][j]));
}
}
}
void transpose(int **a, int **t, int r, int c) //for finding out the transpose of the matrix
{
int i, j;
for (i = 0; i < c; i++)
{
for (j = 0; j < r; j++)
t[i][j] = a[j][i];
}
}
void display(int **a, int r, int c) //for displaying the matrix
{
int i, j;
for (i = 0; i < r; i++)
{
printf("\n");
for (j = 0; j < c; j++)
printf("\t%d", a[i][j]);
}
}
There are many posts about scanf in loops I've seen, but I wasn't able to connect my issue with any of them.

Unhandled exception when adding a value to struct member in 2D array

I am writing a Theater program using a dynamic 2D array. To store a booking details I use structure.
When I try to initialize one of the variables inside each index of 2D array, I receive unhandled exception error.
Function with error:
void initializing_tickets(ticket **arrayPtr, int row, int col){
int i, j, counter;
for(i = 0; i < row; i++)
{
for(j = 0; j < col; j++)
{
(*(arrayPtr + i) + j) -> id = 0; // debugger explains that expression cannot be evaluated
printf("%d ", (*(arrayPtr + i) + j) -> id);
}
printf("\n");
}
} //end of initializing_tickets()
My program so far:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
/* Structures */
typedef struct Theater
{
int id;
int status;
char name[20];
char phone[15];
} ticket;
/* Global variables */
ticket **array2D; // pointer to a 2D array
/* Constructors */
void create_Theater(int *row, int* col);
void test();
void loop_array(ticket **arrayPtr, int row, int col);
void initializing_tickets(ticket **arrayPtr, int row, int col);
int main(void)
{
int row = 0, col = 0;
create_Theater(&row,&col);
initializing_tickets(array2D, row, col);
//loop_array(array2D, row, col);
//test();
printf("\n\n");
system("pause");
return(0);
}
void create_Theater(int *row, int* col)
{
int r = 0, c = 0;
int i;
assert(row);
assert(col);
*row = r;
*col = c;
printf("Please enter the row dimensions of the Theater\n");
scanf("%d", row);
printf("Please enter the column dimensions of the Theater\n");
scanf("%d", col);
array2D = (ticket**)malloc(r*sizeof(ticket*));
for (i = 0;i<r;i++)
{
array2D[i] = (ticket*)malloc(c*sizeof(ticket));
}
} // end of create_Theater()
void initializing_tickets(ticket **arrayPtr, int row, int col){
int i, j, counter;
for(i = 0; i < row; i++)
{
for(j = 0; j < col; j++)
{
(*(arrayPtr + i) + j) -> id = 0; // debugger explains that expression cannot be evaluated
printf("%d ", (*(arrayPtr + i) + j) -> id);
}
printf("\n");
}
} //end of initializing_tickets()
void loop_array(ticket **arrayPtr, int row, int col)
{
int i, j;
for(i = 0; i < row; i++)
{
printf("Row is ok");
for(j = 0; j < col; j++)
{
printf("Col is ok");
}
}
}
I think array is not allocated properly to a memory, but I can't find a mistake.
Thank you for attention!
Change your function to:
void create_Theater(int* row, int* col){
int i;
assert(row);
assert(col);
printf("Please enter the row dimensions of the Theater\n");
scanf("%d", row);
printf("Please enter the column dimensions of the Theater\n");
scanf("%d", col);
array2D = (ticket**)malloc((*row)*sizeof(ticket*));
for (i = 0;i<(*row);i++)
{
array2D[i] = (ticket*)malloc((*col)*sizeof(ticket));
}
} // end of create_Theater()
It works.

c- Allocate and Free 2D Array

I am trying to write 2 functions, one to Dynamic allocation a 2D array,Other to free this 2D array:
int allocate(int **array, unsigned int rows, unsigned int columns){
int i;
for (i = 0; i < rows; i++) {
array[i] = malloc(columns * sizeof (int));
}
/* Code fo fill the array*/
return 1;
}
void de_allocate(int **v, unsigned int rows) {
int i;
for (i = 0; i < rows; i++) {
free(v[i]);
}
free(v);
}
int main(int argc, char **argv) {
int rows, columns;
rows = atoi(argv[1]);
columns = atoi(argv[2]);
int *ipp[rows];
allocate(ipp, rows, columns);
de_allocate(ipp,rows);
return 0;
}
I must respect the allocate function signature :
int allocate(int **array, unsigned int rows, unsigned int columns)
And at the end of allocate function ipp must have access to allocated 2D array.
Allocate function it's right but in de_allocate function i have a SIGABRT Signal
The problem is that you are trying to free a stack allocated var with code free(v);
You could do that if you mallocated the array of pointer, but you declare it locally in main function with int *ipp[rows];
Change it to int **ipp = malloc(sizeof(int*)*rows); if you want to leave de_allocate as is.
You could test it with
#include <stdio.h>
#include <stdlib.h>
int allocate(int **array, unsigned int rows, unsigned int columns){
int i;
for (i = 0; i < rows; i++)
{
array[i] = malloc(columns * sizeof (int));
}
/* Code fo fill the array*/
return 1;
}
void de_allocate(int **v, unsigned int rows) {
int i;
for (i = 0; i < rows; i++)
{
free(v[i]);
}
free(v);
}
int main(int argc, char **argv)
{
int rows, columns;
int temp = 0;
rows = atoi(argv[1]);
columns = atoi(argv[2]);
int **ipp = malloc(sizeof(int*)*rows);
allocate(ipp, rows, columns);
for (int i=0; i<rows; i++)
for (int j=0; j<columns; j++)
ipp[i][j] = temp++;
for (int i=0; i<rows; i++)
for (int j=0; j<columns; j++)
printf("ipp[%d][%d] = %d\n", i, j, ipp[i][j]);
de_allocate(ipp,rows);
return 0;
}
void de_allocate(int **v, unsigned int rows) {
int i;
for (i = 0; i < rows; i++) {
free(v[i]);
}
free(v);
-----^----
here you are attempting to free a variable for which you didn't dynamically allocate memory in the first place
}

crash on trying to reallocate a pointer using pointer to this pointer

I have a pointer to a pointer ("paths") and I want to reallocate each pointer (each "path"). But I get a crash. Generally I am trying to find all possible powers of a number, which one can compute for some amount of operations (e.g for two operations we can get power of three and four (one operation for square of a number, then another one either for power of three or four)). I figured out how to do it on paper, now I am trying to implement it in code. Here is my try:
#include <stdio.h>
#include <stdlib.h>
void print_path(const int *path, int path_length);
int main(void)
{
fputs("Enter number of operations? ", stdout);
int operations;
scanf("%i", &operations);
int **paths, *path, npaths, npath;
npaths = npath = 2;
path = (int*)malloc(npath * sizeof(int));
paths = (int**)malloc(npaths * sizeof(path));
int i;
for (i = 0; i < npaths; ++i) // paths initialization
{
int j;
for (j = 0; j < npath; ++j)
paths[i][j] = j+1;
}
for (i = 0; i < npaths; ++i) // prints the paths, all of them are displayed correctly
print_path(paths[i], npath);
for (i = 1; i < operations; ++i)
{
int j;
for (j = 0; j < npaths; ++j) // here I am trying to do it
{
puts("trying to reallocate");
int *ptemp = (int*)realloc(paths[j], (npath + 1) * sizeof(int));
puts("reallocated"); // tried to write paths[j] = (int*)realloc...
paths[j] = ptemp; // then tried to make it with temp pointer
}
puts("memory reallocated");
++npath;
npaths *= npath; // not sure about the end of the loop
paths = (int**)realloc(paths, npaths * sizeof(path));
for (j = 0; j < npaths; ++j)
paths[j][npath-1] = paths[j][npath-2] + paths[j][j];
for (j = 0; j < npaths; ++j)
print_path(paths[j], npath);
puts("\n");
}
int c;
puts("Enter e to continue");
while ((c = getchar()) != 'e');
return 0;
}
void print_path(const int *p, int pl)
{
int i;
for (i = 0; i < pl; ++i)
printf(" A^%i -> ", p[i]);
puts(" over");
}
I am not sure the problem resides with the call to realloc(), rather you are attempting to write to locations for which you have not created space...
Although you create memory for the pointers, no space is created (allocate memory) for the actual storage locations.
Here is an example of a function to allocate memory for a 2D array of int:
int ** Create2D(int **arr, int cols, int rows)
{
int space = cols*rows;
int y;
arr = calloc(space, sizeof(int));
for(y=0;y<cols;y++)
{
arr[y] = calloc(rows, sizeof(int));
}
return arr;
}
void free2DInt(int **arr, int cols)
{
int i;
for(i=0;i<cols; i++)
if(arr[i]) free(arr[i]);
free(arr);
}
Use example:
#include <ansi_c.h>
int main(void)
{
int **array=0, i, j;
array = Create2D(array, 5, 4);
for(i=0;i<5;i++)
for(j=0;j<4;j++)
array[i][j]=i*j; //example values for illustration
free2DInt(array, 5);
return 0;
}
Another point here is that it is rarely a good idea to cast the return of [m][c][re]alloc() functions
EDIT
This illustration shows my run of your code, just as you have presented it:
At the time of error, i==0 & j==0. The pointer at location paths[0][0] is uninitialized.
EDIT 2
To reallocate a 2 dimension array of int, you could use something like:
int ** Realloc2D(int **arr, int cols, int rows)
{
int space = cols*rows;
int y;
arr = realloc(arr, space*sizeof(int));
for(y=0;y<cols;y++)
{
arr[y] = calloc(rows, sizeof(int));
}
return arr;
}
And here is a test function demonstrating how it works:
#include <stdio.h>
#include <stdlib.h>
int ** Create2D(int **arr, int cols, int rows);
void free2DInt(int **arr, int cols);
int ** Realloc2D(int **arr, int cols, int rows);
int main(void)
{
int **paths = {0};
int i, j;
int col = 5;
int row = 8;
paths = Create2D(paths, col, row);
for(i=0;i<5;i++)
{
for(j=0;j<8;j++)
{
paths[i][j]=i*j;
}
}
j=0;
for(i=0;i<5;i++)
{
for(j=0;j<8;j++)
{
printf("%d ", paths[i][j]);
}
printf("\n");
}
//reallocation:
col = 20;
row = 25;
paths = Realloc2D(paths, col, row);
for(i=0;i<20;i++)
{
for(j=0;j<25;j++)
{
paths[i][j]=i*j;
}
}
j=0;
for(i=0;i<20;i++)
{
for(j=0;j<25;j++)
{
printf("%d ", paths[i][j]);
}
printf("\n");
}
free2DInt(paths, col);
getchar();
return 0;
}
The realloc() does not fail. What fails is that you haven't allocated memory for the new pointers between paths[previous_npaths] and paths[new_npaths-1], before writing to these arrays in the loop for (j = 0; j < npaths; ++j).

Passing a matrix in a function (C)

I have an issue passing a matrix to a function in C. There is the function I want to create:
void ins (int *matrix, int row, int column);
but I noticed that in contrast to the vectors, matrix give me an error. How can I pass my matrix to a function so?
EDIT --> there is the code:
// Matrix
#include <stdio.h>
#define SIZE 100
void ins (int *matrix, int row, int column);
void print (int *matrix, int row, int column);
int main ()
{
int mat[SIZE][SIZE];
int row, col;
printf("Input rows: ");
scanf ("%d", &row);
printf("Input columns: ");
scanf ("%d", &col);
printf ("Input data: \n");
ins(mat, row, col);
printf ("You entered: ");
print(mat, row, col);
return 0;
}
void ins (int *matrix, int row, int column);
{
int i, j;
for (i = 0; i < row; i++)
{
for (j = 0; j < column; j++)
{
printf ("Row %d column %d: ", i+1, j+1);
scanf ("%d", &matrix[i][j]);
}
}
}
void print (int *matrix, int row, int column)
{
int i;
int j;
for(i=0; i<row; i++)
{
for(j=0; j<column; j++)
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
You need to pass a pointer with as much levels of indirection (*) as the number of dimensions of your matrix.
For example, if your matrix is 2D (e.g. 10 by 100), then:
void ins (int **matrix, int row, int column);
If you have a fixed dimension (e.g. 100), you can also do:
void ins (int (*matrix)[100], int row, int column);
or in your case:
void ins (int (*matrix)[SIZE], int row, int column);
If both your dimensions are fixed:
void ins (int matrix[10][100], int row, int column);
or in your case:
void ins (int matrix[SIZE][SIZE], int row, int column);
If you have a modern C compiler you can do the following for 2D matrices of any sizes
void ins (size_t rows, size_t columns, int matrix[rows][columns]);
Important is that the sizes come before the matrix, such that they are known, there.
Inside your function you then can access the elements easily as matrix[i][j] and the compiler is doing all the index calculations for you.
it would also possible to leave the first dimension empty, the same as (*matrix):
void ins (int matrix[][100], int row, int column);
Much better way to use malloc function and create dynamically allocated array and do whatever you want to do using 2d array:
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
void fun(int **arr,int m,int n)
{
int i, j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", &arr[i][j]);
}
}
}
int main()
{
int i,j,m,n;
printf("enter order of matrix(m*n)");
scanf("%d*%d",&m,&n);
int **a=(int **)malloc(m*sizeof(int));
for(i=0;i<n;i++)
a[i]=(int *)malloc(n*sizeof(int));
fun(a,m,n);
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}
output:
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
void fun(int **arr,int m,int n)
{
int i, j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", &arr[i][j]);
}
}
}
int main()
{
int i,j,m,n;
printf("enter order of matrix(m*n)");
scanf("%d*%d",&m,&n);
int **a=(int **)malloc(m*sizeof(int));
for(i=0;i<n;i++)
a[i]=(int *)malloc(n*sizeof(int));
fun(a,m,n);
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}
You can try this as well:
void inputmat(int r,int c,int arr[r * sizeof(int)][c * sizeof(int)])

Resources