This is the only way I know to create a matrix (2D array) in C, dynamically, and reading user input into its elements:
Creating a pointer to an array of x pointers, where each pointer
represents a line in the matrix - x is the number of lines in the matrix (its height).
Pointing each pointer in this array to an array with y elements,
where y is the number of columns in the matrix (the width).
int main()
{
int i, j, lines, columns, **intMatrix;
printf("Type the matrix lines:\t");
scanf("%d", &lines);
printf("Type the matrix columns:\t");
scanf("%d", &columns);
intMatrix = (int **)malloc(lines * sizeof(int *));
//pointer to an array of [lines] pointers
for (i = 0; i < lines; ++i)
intMatrix[i] = (int *)malloc(columns * sizeof(int));
//pointer to a single array with [columns] integers
for (i = 0; i < lines; ++i)
{
for (j = 0; j < columns; ++j)
{
printf("Type a number for <line: %d, column: %d>\t", i+1, j+1);
scanf("%d", &intMatrix[i][j]);
}
}
Are there other ways to do this?
You can try like this
int main()
{
int i, j, lines, columns, *intMatrix;
printf("Type the matrix lines:\t");
scanf("%d", &lines);
printf("Type the matrix columns:\t");
scanf("%d", &columns);
intMatrix = (int *)malloc(lines * columns * sizeof(int));
for (i = 0; i < lines; ++i)
{
for (j = 0; j < columns; ++j)
{
printf("Type a number for <line: %d, column: %d>\t", i+1, j+1);
scanf("%d", &intMatrix[i*lines + j]);
}
}
From C99 onwards (but not C++), you can use variable length arrays:
int main()
{
int i, j, lines, columns;
printf("Type the matrix lines:\t");
scanf("%d", &lines);
printf("Type the matrix columns:\t");
scanf("%d", &columns);
{
int intMatrix[lines][columns];
for (i = 0; i < lines; ++i)
{
for (j = 0; j < columns; ++j)
{
printf("Type a number for <line: %d, column: %d>\t", i+1, j+1);
scanf("%d", &intMatrix[i][j]);
}
}
}
}
Or even like this:
void readData (int lines, int columns, int array[lines][columns])
{
int i, j;
for (i = 0; i < lines; ++i)
{
for (j = 0; j < columns; ++j)
{
printf("Type a number for <line: %d, column: %d>\t", i+1, j+1);
scanf("%d", &array[i][j]);
}
}
}
int main()
{
int lines, columns;
printf("Type the matrix lines:\t");
scanf("%d", &lines);
printf("Type the matrix columns:\t");
scanf("%d", &columns);
{
int intMatrix[lines][columns];
readData (lines, columns, intMatrix);
}
}
But, in both cases, the array data is all stored on the stack, not the heap, so there's no way to store it properly, and you can't put it in a struct or anything malloc'd.
struct matrix {
type *mem;
};
struct matrix* matrix_new () {
struct matrix *M = malloc (sizeof(matrix));
M->mem = malloc (sizeof (type) * rows * cols);
return M;
}
use realloc,memcpy,memmove and free to modify chunks of the array. To access single elemnts use something like mem[row*cols+col] or mem[rows*col+row] depend on what has priority for you (or what you define a row and a column).
Related
Here in this code I am trying to dynamically allocate memory to a 2d array and print it The problem I face here is I cant get the output properly lets assume my input is an 2d array of size 2*2 [1,2,3,4] but the output printed is [1,1,1,1].
#include <stdio.h>
#include <stdlib.h>
int output_func(int row, int col, int *ptr)
{
printf("\nThis is your first matrix: \n\n");
for (int i = 0; i < row; i++)
{
printf("\t |");
for (int j = 0; j < col; j++)
{
printf(" %d ", *ptr);
}
printf("|\n");
}
}
int main()
{
int **ptr;
int row, col;
int i, j;
printf("enter the no of rows for the matrix: ");
scanf("%d", &row);
printf("enter the no of col for the matrix: ");
scanf("%d", &col);
ptr = (int **)malloc(row * sizeof(int *));
for (int i = 0; i < row; i++)
{
ptr[i] = (int *)malloc(col * sizeof(int));
}
// input of first matrix
printf("\nEnter the elements for first matrix :\n");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
printf("\t A[%d,%d] = ", i, j);
scanf("%d", &ptr[i][j]);
}
}
output_func(row, col, *ptr);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
// int* ptr -> int** ptr
void output_func(int row, int col, int** ptr)
{
printf("\nThis is your first matrix: \n\n");
for (int i = 0; i < row; i++)
{
printf("\t |");
for (int j = 0; j < col; j++)
{
// *ptr -> ptr[i][j]
printf(" %d ", ptr[i][j]);
}
printf("|\n");
}
}
int main()
{
int** ptr;
int row, col;
printf("enter the no of rows for the matrix: ");
scanf("%d", &row);
printf("enter the no of col for the matrix: ");
scanf("%d", &col);
ptr = (int**)malloc(row * sizeof(int*));
for (int i = 0; i < row; i++)
{
ptr[i] = (int*)malloc(col * sizeof(int));
}
// input of first matrix
printf("\nEnter the elements for first matrix :\n");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
printf("\t A[%d,%d] = ", i, j);
scanf("%d", &ptr[i][j]);
}
}
output_func(row, col, ptr);
return 0;
}
If you want a function to print the array allocated using an array of pointers to arrays of int (also known as a jagged array), you must pass the pointer to the array of pointers.
In other words - this is wrong:
int output_func(int row, int col, int *ptr)
^^^^^^^^
A int-pointer but you want
a pointer to a pointer to int
which is "int **ptr"
So do
int output_func(int row, int col, int **ptr)
{
printf("\nThis is your first matrix: \n\n");
for (int i = 0; i < row; i++)
{
printf("\t |");
for (int j = 0; j < col; j++)
{
printf(" %d ", ptr[i][j]);
}
printf("|\n");
}
}
and call it like:
output_func(row, col, ptr);
We must use functions, loops, data types, and pointers. I am honestly confused about pointers and how to use them in this context. I know they point to the memory address of a data type? I was wondering if maybe it would be possible to make the getElement function return a pointer to the array and then make the printArray function take a pointer as a parameter? would that work or is there a better way to do this.
Anyways this is what I have so far:
# include <stdio.h>
void getElement(int[][]arr, int row, int column){
for(int i=0; i< row;i++){
for(int k = 0; k< column; i++){
printf("Enter value for index [%i] [%i]: \n", i,k);
scanf("%i", arr[i][k]);
}
}
}
void printArray(int **arr, int row, int column){
printf("\nOutput Matrix:\n");
for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
printf("%d ", arr[i][j]);
if (j == column - 1)
printf("\n");
}
}
int main(){
int mat1[10][10],mat2[10][10],result[10][10], r1,r2,c1,c2;
printf("Enter rows and colums for first array: ");
scanf("%i %i",r1,c1);
printf("Enter rows and colums for second array: ");
scanf("%i %i",r2,c2);
while (r1 != c2){
printf("not doable, Enter value for rows and colums of first array ");
scanf("%i %i",r1,c1);
printf("Enter rows and colums for second array: ");
scanf("%i %i",r2,c2)
}
}
return 0;
}
My background is java so I'm not used to c syntax yet.
I need to do the following: let the user to input number k (number of rows), and after to insert values into 2d array with this form:
1 2
3 4
5 6
i.e two values with space between them and then new line for the new row.
If the user entered k=1000 but entered only 4 rows so the function call would be only with the array with 4 rows and not 100. the loop that reads the values should stop if: there are k rows or reaching to EOF
My questions:
I don't know how to implement the EOF part.
I don't know how to implement that for k=1000 and there only 4 rows so call the function with the array that contains only 4 rows
Here my code:
#include <stdio.h>
#define COLS 2
void foo(int** rows, int n);
int main()
{
int k;
printf("Please enter number of rows\n");
scanf_s("%d", &k);
int** matrix = (int**)malloc(k * sizeof(int*));
for (int i = 0; i < k; i++)
matrix[i] = (int*)malloc(COLS * sizeof(int));
int num1, num2;
for (int i = 0; i < k||num1!=EOF; i++)
{
printf("Enter two numbers separated by space \n");
scanf_s("%d %d", &num1, &num2);
matrix[i][0]=num1;
matrix[i][1] = num2;
}
printf("The array:: \n");
for (int i = 0; i < k; i++)
{
for (int j = 0; j < COLS; j++)
{
printf("%d \t",matrix[i][j]);
}
printf("\n");
}
foo(matrix, k);
for (int i = 0; i < k; i++)
{
free(matrix[i]);
}
free(matrix);
return 0;
}
void foo(int** rows, int n)
{
//some stuff
}
Change the bellow portion of your code:
for (int i = 0; i < k||num1!=EOF; i++)
{
printf("Enter two numbers separated by space \n");
scanf_s("%d %d", &num1, &num2);
matrix[i][0]=num1;
matrix[i][1] = num2;
}
To:
int i;
for (i = 0; i < k; i++)
{
printf("Enter two numbers separated by space \n");
if(2 != scanf_s("%d %d", &num1, &num2)) break;
matrix[i][0]=num1;
matrix[i][1] = num2;
}
k = i;
Hope it will work as you want
check the return value of scanf
for (int i = 0; i < k; i++)
{
printf("Enter two numbers separated by space \n");
if(scanf_s("%d %d", &num1, &num2)==EOF)
break;
matrix[i][0]=num1;
matrix[i][1] = num2;
}
I made a program that adds two matrices and displays their sum with a max dimension of 100.
/* This program asks the user for 2 matrices called A and B, as integers,
and displays their sum, C. The max dimension of each matrix is 100. */
#include <stdio.h>
// Construct function
void construct()
{
int m, n, i, j; // Variables
int first[100][100], second[100][100], sum[100][100]; // Matrices variables
printf("Please enter the number of rows: ");
scanf("%d", &m);
printf("Please enter the number of columns: ");
scanf("%d", &n);
// User enters m x n amount whole numbers for the Matrix A
printf("Enter Matrix A\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &first[i][j]);
// User enters m x n amount whole numbers for the Matrix B
printf("Enter Matrix B\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &second[i][j]);
// Adds the sum of Matrix A and Matrix B
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
sum[i][j] = first[i][j] + second[i][j];
// Display the sum of Matrix A and Matrix B
printf("A + B =\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
printf("%d ", sum[i][j]);
printf("\n"); // Prints new line
}
return ;
}
// Main Function
int main()
{
construct(); // Calls construct function
return 0;
}
Now I need to change it so there is no max size for each matrix.
So I need to use malloc to create my arrays.
So I cant use int A[rows][cols].
This is what I did to covert arrays to malloc. It compiles but it crashes after I entered all the integers. Need help.
/* This program asks the user for 2 matrices called A and B, as integers,
and displays their sum, C. The max dimension of each matrix is 100. */
#include <stdio.h>
#include <stdlib.h>
// Construct function
void construct()
{
int m, n, i, j; // Variables
int *first = NULL;
int *second = NULL;
int *sum = NULL; // Matrices variables
printf("Please enter the number of rows: ");
scanf("%d", &m);
printf("Please enter the number of columns: ");
scanf("%d", &n);
first = (int*)malloc(m * sizeof(int));
second = (int*)malloc(n * sizeof(int));
sum = (int*)malloc(m * n * sizeof(int));
// User enters m x n amount whole numbers for the Matrix A
printf("Enter Matrix A\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &first);
// User enters m x n amount whole numbers for the Matrix B
printf("Enter Matrix B\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &second);
// Adds the sum of Matrix A and Matrix B
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
sum = *first + *second;
// Display the sum of Matrix A and Matrix B
printf("A + B =\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
printf("%d ", sum);
printf("\n");
}
return ;
}
// Main Function
int main()
{
construct(); // Calls construct function
return 0;
}
First of all, you don't need to use malloc. Just move the array definitions to be after you have inputted m and n:
int first[m][n];
printf("Enter Matrix A\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &first[i][j]);
and similarly for second and sum.
If the matrices might be larger than 100x100 then it might be good to use malloc to avoid the risk of a stack overflow; the way to do that is:
int (*first)[n] = malloc(m * sizeof *first);
printf("Enter Matrix A\n");
// etc.
and at the end, free(first);. No other changes are required.
In your attempt to use malloc, you didn't allocate enough space, and you didn't scanf into the space you allocated either (instead you overwrote the pointer to the allocated space).
I'm trying to ask the user to enter the number of columns and rows they want in a matrix, and then enter the values in the matrix... I'm going to let them insert numbers one row at a time.
How can I create such function ?
#include<stdio.h>
main(){
int mat[10][10],i,j;
for(i=0;i<2;i++)
for(j=0;j<2;j++){
scanf("%d",&mat[i][j]);
}
for(i=0;i<2;i++)
for(j=0;j<2;j++)
printf("%d",mat[i][j]);
}
This works for entering the numbers, but it displays them all in one line... The issue here is that I don't know how many columns or rows the user wants, so I cant print out %d %d %d in a matrix form...
Any thoughts?
Thanks :)
How about the following?
First ask the user for the number of rows and columns, store that in say, nrows and ncols (i.e. scanf("%d", &nrows);) and then allocate memory for a 2D array of size nrows x ncols. Thus you can have a matrix of a size specified by the user, and not fixed at some dimension you've hardcoded!
Then store the elements with for(i = 0;i < nrows; ++i) ... and display the elements in the same way except you throw in newlines after every row, i.e.
for(i = 0; i < nrows; ++i)
{
for(j = 0; j < ncols ; ++j)
{
printf("%d\t",mat[i][j]);
}
printf("\n");
}
You need to dynamically allocate your matrix. For instance:
int* mat;
int dimx,dimy;
scanf("%d", &dimx);
scanf("%d", &dimy);
mat = malloc(dimx * dimy * sizeof(int));
This creates a linear array which can hold the matrix. At this point you can decide whether you want to access it column or row first. I would suggest making a quick macro which calculates the correct offset in the matrix.
need a
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d",mat[i][j]);
}
printf("\n");
}
#include<stdio.h>
int main(void)
{
int mat[10][10],i,j;
printf("Enter your matrix\n");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{
scanf("%d",&mat[i][j]);
}
printf("\nHere is your matrix:\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d ",mat[i][j]);
}
printf("\n");
}
}
This is my answer
#include<stdio.h>
int main()
{int mat[100][100];
int row,column,i,j;
printf("enter how many row and colmn you want:\n \n");
scanf("%d",&row);
scanf("%d",&column);
printf("enter the matrix:");
for(i=0;i<row;i++){
for(j=0;j<column;j++){
scanf("%d",&mat[i][j]);
}
printf("\n");
}
for(i=0;i<row;i++){
for(j=0;j<column;j++){
printf("%d \t",mat[i][j]);}
printf("\n");}
}
I just choose an approximate value for the row and column. My selected row or column will not cross the value.and then I scan the matrix element then make it in matrix size.
int rows, cols , i, j;
printf("Enter number of rows and cols for the matrix: \n");
scanf("%d %d",&rows, &cols);
int mat[rows][cols];
printf("enter the matrix:");
for(i = 0; i < rows ; i++)
for(j = 0; j < cols; j++)
scanf("%d", &mat[i][j]);
printf("\nThe Matrix is:\n");
for(i = 0; i < rows ; i++)
{
for(j = 0; j < cols; j++)
{
printf("%d",mat[i][j]);
printf("\t");
}
printf("\n");
}
}
//R stands for ROW and C stands for COLUMN:
//i stands for ROW and j stands for COLUMN:
#include<stdio.h>
int main(){
int M[100][100];
int R,C,i,j;
printf("Please enter how many rows you want:\n");
scanf("%d",& R);
printf("Please enter how column you want:\n");
scanf("%d",& C);
printf("Please enter your matrix:\n");
for(i = 0; i < R; i++){
for(j = 0; j < C; j++){
scanf("%d", &M[i][j]);
}
printf("\n");
}
for(i = 0; i < R; i++){
for(j = 0; j < C; j++){
printf("%d\t", M[i][j]);
}
printf("\n");
}
getch();
return 0;
}