I have a problem with this program, the program must simply output the minimum value contained in a matrix, this must be done by the function that has as parameter the double pointer (**A) that would be the array , the problem is that after inserting the items , the program finishes and returns nothing.
(I don’t even appear written outuput instruction )
#include<stdio.h>
#include<stdlib.h>
int minium_matrix_value(int **A, int rows, int columns) {
int min=A[0][0];
for(int i=0;i<rows;i++){
for(int j=0;j<columns;j++)
if(A[i][j]<min)
min=A[i][j];
}
return min;
}
int main(){
int** A;
int i, j;
int result;
int sizer=100, sizec=100;
A = (int**)calloc(sizer,sizeof(int*));
A = (int**)calloc(sizec,sizeof(int*));
printf("insert rows size");
scanf("%d",&sizer);
printf("insert columns size");
scanf("%d",&sizec);
printf("insert matrix elements");
for( i=0; i < sizer; i++ )
for( j=0; j < sizec; j++ ) {
scanf("%d",((A+i)+j));
}
result=minium_matrix_value(A,sizer,sizec);
printf("the minium elements is: %d",result);
return 0;
}
You only allocated arrays to store pointers to rows. You have to allocate arrays for storing values of each rows.
Using the value of sizer should be after reading value into that/
// move this after scanf()
// A = (int**)calloc(sizer,sizeof(int*));
// remove this, or memory leak occur
// A = (int**)calloc(sizec,sizeof(int*));
printf("insert rows size");
scanf("%d",&sizer);
printf("insert columns size");
scanf("%d",&sizec);
// move here
A = calloc(sizer,sizeof(int*));
printf("insert matrix elements");
for( i=0; i < sizer; i++ ) { // add { to do multiple things
A[i] = calloc(sizec,sizeof(int)); // allocate row array
for( j=0; j < sizec; j++ ) {
//scanf("%d",((A+i)+j));
scanf("%d",&A[i][j]); // use array style, which should be easier to understand
}
} // add } to do multiple things
Also note that:
scanf("%d",((A+i)+j)); is wrong and it should be scanf("%d",(*(A+i)+j)); if you hate [] operator.
Casting result of malloc() family is discouraged in C.
Related
`
//MATRIX INPUT
#include<stdio.h>
int main(void)
{
//declaring variables
size_t row=0;
size_t column=0;
int limit=0;
int en=0;
int mat[row][column];
//starting
printf("ENTRE THE NUMBER OF R
EPETITIONS OF MATRIX
INPUT:");
scanf("%d",&limit);
//starting loop
for(int i=0;i<=(limit-1);++i)
{
printf("\nINITIALIZED THE
MATRIX-%d...\n",i+1);
printf("\nENTER ROW
NUMBER FOR MATRIX:\n");
scanf("%d",&row);
printf("\nENTER COLUMN
NUMBER FOR MATRIX:\n");
scanf("%d",&column);
//entering the entries..
for(int j=0; j<row ;++j)
{
for(int k=0;
k<column;++k)
{
printf("ENTRY (%d,%d):",(j+1),(k+1));
scanf("%d",&mat[k][j]);
}
}
}
//starting the console output
of matrix
int v=0;
printf("Which matrix do you
want to see?\n");
scanf("%d",&v);
for(v=0; v<=limit; ++v)
{
for(int l=0; l<row; ++l)
{
for( int m=0; m<column;
++m)
{
printf("%2d", mat[m][l]);
}
}
}
return 0;
}`
I have written a program in C where the user can firstly define the number of matrices. Then, the dimension of individual matrix is defined. I have successfully proceeded to individual matrix input. But I am stuck in writing the operational codes like multiplying and adding matrices as well as to write code for showing output in matrix style.
How to fix this?
incomplete source code
Console of output
I couldn't get the part why you created an empty static array, and then changed its boundaries at least tried to change. However, I believe dynamic array allocation would serve your purpose better than static one. I implemented a 3D array that has the first index as matrices, the second index as rows of the current matrix, and the third index as columns of the current matrix. Also, fixed the display method, you have been using. However, there can be different-sized matrices for each matrix you have. Therefore, I implemented another list to keep track of the rows and columns. Lastly, I put two links at the top of the code that you can implement addition and multiplication operations by yourself. You can see the code from here:
//MATRIX INPUT
#include<stdio.h>
#include<stdlib.h>
//Add two matrices
//https://www.programmingsimplified.com/c-program-add-matrices
//Multiplying two matrices
//https://www.programiz.com/c-programming/examples/matrix-multiplication
void display_matrix(int** , int , int );
void fillWithNum(int**,int,int,int);
int main(void)
{
//declaring variables
size_t row=0;
size_t column=0;
int limit=0;
int en=0;
int ***mat;
//starting
printf("ENTRE THE NUMBER OF REPETITIONS OF MATRIX INPUT:");
scanf("%d",&limit);
mat = (int***)malloc(sizeof(int**) * limit);
//Two keep track of the rows and columns
//First index of the second dimension will be rows, and
//second index will be columns of matrices at the mat variable.
int **indexingList;
indexingList = (int**)malloc(sizeof(int*) * limit);
for(int i=0;i<limit;++i) {
indexingList = (int*) malloc(sizeof(int) * 2);
}
//starting loop
for(int i=0;i<limit;i++)
{
printf("\nINITIALIZED THE MATRIX-%d...\n",i+1);
printf("\nENTER ROW NUMBER FOR MATRIX:\n");
scanf("%d",&row);
printf("\nENTER COLUMN NUMBER FOR MATRIX:\n");
scanf("%d",&column);
mat[i] = (int**) malloc(row * sizeof(int*));
for (int j = 0;j < row;j++) {
mat[i][j] = (int*)malloc(column * sizeof(int));
}
//entering the entries..
for(int j=0;j < row;j++)
{
for(int k=0;k < column;k++)
{
printf("ENTRY (%d,%d):",(j+1),(k+1));
scanf("%d",&mat[i][j][k]);
}
}
indexingList[i][0] = row;
indexingList[i][1] = column;
}
//starting the console output of matrix
int v=1;
printf("Which matrix do you want to see?\n");
scanf("%d",&v);
//v-1 because if user want to display first matrix it should be 0, so user will enter 1
//therefore, 1-1 will give us 0 to display 0 index matrix
display_matrix(mat[v-1], indexingList[v-1][0], indexingList[v-1][1]);
//Problem at freeing memory for some purpose crash at here.
//I couldn't figure it out as well.
for(int i = 0;i < limit;i++) {
for(int j = 0;j < indexingList[i][0];j++) {
free(mat[i][j]);
}
free(mat[i]);
}
free(mat);
for(int i = 0;i < limit;i++) {
free(indexingList[i]);
}
free(indexingList);
return 0;
}
void display_matrix(int** matrix, int r, int c) {
for(int i = 0 ;i < r;i++){
for(int j = 0;j < c;j++) {
printf("%d\t",matrix[i][j]);
}
printf("\n");
}
}
//Test purpose
void fillWithNum(int** arr,int r, int c, int num) {
for (int i = 0;i<r;i++) {
for(int j = 0;j<c;j++) {
arr[i][j] = num;
}
}
}
However, this code also crashes at the end of the memory-freeing part. I couldn't figure out why, but if someone finds it out as well, I would appreciate it.
#include <stdio.h>
int main()
{
//Initialize array
int n; // n is use to decide the size of array
int x[n];
int y[n];
printf("enter the size of array:");
scanf("%d", &n);
if (n > 0)
{
for (int i = 0; i < n; i++)
{
printf("enter elements : \n");
scanf("%d", &x[i]);
}
}
printf("Array in reverse order: \n");
//Loop through the array in reverse order
for (int i = n - 1, j = 0; i >= 0; i--, j++)
{
y[j] = x[i];
printf("%d ", y[j]);
}
return 0;
}
In the above program, I have created a array whose size can be decided by the user. The user can also put elements in it.
After that I want to reverse this array and store the data in another array. But I get this error again and again. I am using CodeBlocks with the GCC compiler.
When the x and y arrays are created, n is uninitialized. There's no knowing how large these arrays will be. You loops are almost certainly accessing the array out of bounds.
You want to read n, then create the arrays. Of course you also want to error check the result of scanf.
int n; // n is use to decide the size of array
printf("enter the size of array:");
scanf("%d", &n);
int x[n];
int y[n];
I'm writing a program which scanf integers and printf in double.
Here is my code:
int main(void) {
int arraySize;
scanf("%d",&arraySize);
double vector[arraySize];
for(int i=0;i<arraySize;i++) scanf("%lf", &vector[i]);
for(int a=0;a<arraySize;a++) printf("VECTORS:[%lf]",vector[a]);
}
Since I need to for loop every element in the array then printf all of them one by one.
this is the output I had:
VECTORS:[1.000000] VECTORS:[2.000000] VECTORS:[3.000000]
How can I change the format of the printf function and get ouput like this:
VECTOR: [ 1.000, 2.000, 3.000 ]
Your one major mistake is your array size. I know your compiler won't issue any warning but this is not any feature which language provide so size must be a
constant numerical value or const expression.
So in short you can't create array After asking size from user. This is completely wrong.
int arraySize;
scanf("%d",&arraySize);
double vector[arraySize];
You must make size const. If you want less values than the declared size you can decrease the no of times for loop will run but you can't decide array size as inputted by user.
const int size = 10; // this is how your size should be. Even your compiler allowed VLA you should not try this. size of arrays must be constant.
int main()
{
unsigned int i,s;
int arr[size];
printf ("Enter the size of array.");
scanf("%d",&s);
for(i = 0 ; i<s;i++){
scanf("%d",&arr[i]);
}
for(i = 0 ; i<s;i++){
arr[i] = arr[i]*arr[i];
}
for(i = 0 ; i<s;i++){
printf("%d",arr[i]);
}
}
Print VECTOR once then loop over all the vectors and output them in the desired format.
const int size = 10;
int main(void) {
double vector[size];
for(int i=0;i<size;i++)
scanf("%lf", &vector[i]);
printf("VECTOR: [ ");
for(int a=0;a<size;a++){
printf("%lf", vector[a]);
if(i < size - 1)
printf(", ");
}
printf(" ]");
}
You need to allocate memory dynamically to use it.
Use the printf in the code below to define precision.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int arraySize = 0;
scanf("%d",&arraySize);
double *vector = (double *) calloc(arraySize, sizeof(double));
for(int i=0; i<arraySize; i++) {
scanf("%lf", &vector[i]);
}
printf("VECTORS:[");
int a;
for(a=0;a<arraySize;a++) {
printf(" %.3lf",vector[a]);
if (a<(arraySize-1)) {
printf(",");
} else {
printf(" ");
}
}
printf("]");
}
Change your for loop to take 3 elements at once.
for(a=0;a<arraySize;a+=3) {
printf("VECTORS:[%lf", vector[a]);
if (a+1 < arraySize) printf(", %lf", vector[a+1]);
if (a+2 < arraySize) printf(", %lf", vector[a+2]);
printf("]\n");
}
i have been searching and trieng to solve this problem for hours , i searched the internet and for some reason everytime i adjust a problem another one pops
basiclly i want to enetr values from user to a 2d array that it's size is unkown ( i also get it as an input) , and then i just want to pass this 2d array as an argument to a function like a regular 2d array ( arr[k][numElements] )
because the size of the 2d array in unkown i allocated the 2d array , then i tried to use scanf to enter valuse to the array but i get this error :
subscripted value is neither array nor pointer nor vector
also when i try to pass the array to my functio i get errors
(i prefer not to chane the function beacause i worked really hard to make it work lol)
int main()
{
int numElements;
int n; // number of elements
int k; // number of parts
scanf("%d",&n);
scanf("%d",&k);
numElements=n/k;
int length_of_array = k* numElements;
int *arr = (int *)malloc( length_of_array * sizeof(int));
for(int i=0 ; i<k ; i++){
for(int j=0 ; j<numElements ; j++){
scanf("%d", arr[k][numElements]);
}
}
int* output = (int*)malloc(sizeof(int)*n);
divide(0, k - 1, output, numElements,k, arr);
// Print merged array
printf("\n________________________________________________________________\n");
for(int i=0 ; i<n ; i++){
//scanf("%d",output+i);
printf("%d ",*(output+i));
}
}
//and this the function devide that i am trieng to pass the array to :
void divide(int l, int r, int* output, int numElements , int k , int arr[k][numElements] );
here i get the following error :
expected 'int (*)[(sizetype)(numElements)]' but argument is of type
'int'
int main()
{
int n, m; // number of elements
scanf("%d",&n); // n no. of rows
scanf("%d",&m); // m no. of columns
int arr[n][m]; //creating n*m memory spaces- runtime allocation
for(int i=0 ; i<n ; i++){
for(int j=0 ; j<m ; j++){
scanf("%d", &arr[i][j]); //for each row takes n no. of column values
}
}
int* output = (int*)malloc(sizeof(int)*n);
divide(0,n-1,arr); //passing lower index, upper index , the array
// Print merged array
printf("\n________________________________________________________________\n");
for(int i=0 ; i<n ; i++){
//scanf("%d",output+i);
printf("%d ",*(output+i));
}
}
So i have this example:
3 4 6 11 4 6 38 7 6 9
I need to get from user several numbers and create multi dimension array.
The first number N (3 in my example) mean that my array (or matrix) will contain N² value and insert all this numbers (the next 9 values) into my array.
So first i need to define the array according my first value (3 in my example) and create my array:
int a[3][3];
The catch here is that i need to get all my input in a single line so i cannot use this:
int marks[3];
int i;
for(i=0;i<3;i++)
{
printf("Enter a no\n");
scanf("%d",(marks+i));
}
scanf reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments.
scanf will store whole the input from stdin, so it really does not matter if it is in single line or not. The way for your code is just, simply ask user for dimensions and create the variable of the given dimension and fill each value with a scanf.
There are 3 ways to do it :
If your compiler supports variable length array:
int size,i,j;
scanf("%d",&size);
int matrix[size][size];
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
scanf("%d",&matrix[i][j]);
}
}
Does not support variable length array: (using array of pointers)
int size,i,j;
scanf("%d",&size);
int **matrix;
matrix = (int **)malloc(sizeof(int *) * size);
for(i=0;i<size;i++)
{
matrix[i] = (int *)malloc(sizeof(int) * size);
}
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
scanf("%d",&matrix[i][j]);
}
}
This looks easy but the way is very poor as it is not actually an 2D array but an array of pointers. hence, I suggest to use the 3rd way if your compiler does not support variable length array.
Using malloc: (with pointer)
Create Array of integers like:
int size;
scanf("%d",&size);
int *matrix;
matrix = (int *) malloc( sizeof(int) * size * size );
Now, to fill or get the values of the Array you need to traverse to the particular value.
to fill:
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
scanf("%d", (matrix + i*(size) + j));
}
}
to iterate: (print in this case)
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
printf("%d " ,*(matrix+ i*size + j) );
}
printf("\n");
}
Note: It is very important to constrain the input and check whether it lies in some fixed range or not. for ex: ( 0 < size < 100). It is very simple and you can do it yourself. I have answered the important parts only :)
To begin with, you can't store 10 numbers in a 3x3 matrix. Always make sure your specification makes sense before you start programming.
Taking the input is trivial, just use a nested loop to control where the read input ends up in your matrix. Example with a fixed array size:
#include <stdio.h>
#include <stdlib.h>
#define x 3
#define y 3
int main (void)
{
int arr[x][y];
printf("Enter %d numbers: ", x*y);
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
scanf(" %d", &arr[i][j]);
}
}
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
(Note that this leaves a whole lot of junk like line feed characters behind in stdin. There's also no buffer overflow protection. See How to read / parse input in C? The FAQ for examples of how to read input properly.)
If you need a variable size matrix, you can use variable length arrays (VLA):
size_t x = 3; // some run-time value
size_t y = 3; // some run-time value
int arr[x][y];
... // then same code as above
Alternatively, you can use a dynamically allocated 2D array:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
size_t x = 3;
size_t y = 3;
int (*arr)[y] = malloc( sizeof(int[x][y]) );
printf("Enter %zu numbers: ", x*y);
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
scanf(" %d", &arr[i][j]);
}
}
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
printf("%d ", arr[i][j]);
}
printf("\n");
}
free(arr);
return 0;
}
Alternatively, if your compiler is from the Jurassic period, you can use old style "mangled" 2D arrays:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
size_t x = 3;
size_t y = 3;
int* mangled = malloc(x * y * sizeof *mangled);
printf("Enter %zu numbers: ", x*y);
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
scanf(" %d", &mangled[i*x + j]);
}
}
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
printf("%d ", mangled[i*x + j]);
}
printf("\n");
}
free(mangled);
return 0;
}
The above 4 alternatives are the only alternatives. You should not use "pointer-to-pointer look-up tables", there is absolutely no need for them here. Unfortunately, lots of bad books and bad teachers spread that technique. See Correctly allocating multi-dimensional arrays.
Try this:
int** InitMatrix()
{
int** matrix = NULL;
int n;
if (scanf("%d", &n) > 0 && n > 0)
{
matrix = malloc(n * sizeof(int*));
for (int i = 0; i < n; i++)
{
matrix[i] = malloc(n * sizeof(int));
for (int j = 0; j < n; j++)
{
if (scanf("%d", &matrix[i][j]) == 0)
{
// user input error; decide what to do here
}
}
}
}
else
{
// user input error; decide what to do here
}
return matrix;
}