Segmentation Fault During Matrix Multiplication - c

I am new to C coding, and am trying to implement standard matrix multiplication. My code works fine for square matrices, but refuses to accept a column vector. Here is my attempt at the code. Any help would be much appreciated.
//---------------------------------------IMPORTING NECESSARY C PACKAGES AND DEFINING EXECUTION CONSTANTS-------------------------------------------//
#include <stdio.h> // Standard input output library
#include <math.h> // Mathematical function library
#include <stdlib.h> // General purpose standard library
#define true 1
#define false 0
typedef long double numeric; // Using the long double datatype to avoid overflows during computations
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//----------------------------------------------------------------FUNCTION DECLERATION-------------------------------------------------------------//
numeric **create_matrix(int x, int y); // To dynamically allocate memory and create a matrix
void input_matrix(numeric **matrix, int m, int n); // To accept a matrix
void print_matrix(numeric **l, int x, int y); // To print a matrix
numeric **standard_matrix_multiplication(int m, int n, int l); // To multiply two matrices
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//------------------------------------------------------------------DRIVER CODE--------------------------------------------------------------------//
int main(int argc, char *argv[]) {
int m, n, l; int choice;
printf("Enter the matrix operation to be performed using the corresponding index number.\n");
printf("\n");
printf("1.\tMatrix Multiplication");
printf("\n");
scanf("%d", &choice);
switch(choice) {
case 1 :
printf("Enter the number of rows in the first matrix\n");
scanf("%d", &m);
printf("Enter the number of columns in the first matrix\n");
scanf("%d", &n);
printf("Enter the number of columns in the second matrix\n");
scanf("%d", &l);
printf("Enter both matrices.\n");
numeric **matrix_x;
matrix_x = create_matrix(m, l);
matrix_x = standard_matrix_multiplication(m, n, l);
print_matrix(matrix_x, m, l);
break;
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//----------------------------------------------------------MATRIX MULTIPLICATION IMPLEMENTATIONS--------------------------------------------------//
numeric **standard_matrix_multiplication(int m, int n, int l) {
numeric **matrix_a; numeric **matrix_b; numeric **matrix_k;
matrix_a = create_matrix(m, n);
matrix_b = create_matrix(n, l);
matrix_k = create_matrix(m, l);
input_matrix(matrix_a, m, n);
print_matrix(matrix_a, m, n);
input_matrix(matrix_b, n, l);
for(int i = 0; i < m; i++) {
for (int j = 0; j < n; j ++) {
for (int k = 0; k < l; k++) {
matrix_k[i][j] += matrix_a[i][k] * matrix_b[k][j];
}
}
}
return matrix_k;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//---------------------------------------------------------------HELPER FUNCTIONS------------------------------------------------------------------//
numeric **create_matrix(int x, int y) {
numeric **matrix = (numeric**)malloc(x * sizeof(numeric*)); // Dynamically creating an array of pointers
for (int i = 0; i < y; i++) {
matrix[i] = (numeric*)malloc(y * sizeof(numeric)); // Dynamically allocating memory for each columns of the matrix
}
return matrix;
}
void input_matrix(numeric **matrix, int m, int n) {
printf("Enter the elements of the matrix, row wise.\n"); // Instructing the user on matrix entry
printf("For example, to enter the matrix\n");
printf("\t\t1\t2\n");
printf("\t\t3\t4\n");
printf("enter 1, 2, 3, and 4 in that order.\n");
for (int i = 0; i < m; i++) { // Iterating through the rows and columns of the matrix
for (int j = 0; j < n; j++) {
scanf("%Lf", &matrix[i][j]); // Accepting each element
}
}
}
void print_matrix(numeric **l, int x, int y) { // To print a matrix
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
printf("%0.10Lf\t", l[i][j]); // Printing numeric type values
}
printf("\n");
}
printf("\n");
}
As of now, I have only written one switch case, and that is for matrix multiplication. So I chose 1. I gave 2, 1, 2 as my inputs for the number of rows in the first matrix, number of columns in the first matrix, and number of columns in the second matrix respectively. I have given a print statement in line 52, and it isn't executing it for the above input, giving a segmentation fault instead. Could someone please help me out?

Yes there are some issues with your code that gives segfault error during runtime.
The Matrix multiplication logic part of the code needs to be corrected as follows
for(int i = 0; i < m; i++) {
for (int j = 0; j < l; j ++) {
for (int k = 0; k < n; k++) {
matrix_k[i][j] += matrix_a[i][k] * matrix_b[k][j];
because k should iterate till the no of columns in 1st matrix which is n but not till l.
And there is a slight correction needed in create_matrix function.
You use y (i.e. no of columns in the matrix) in your for instead of x (no of rows in matrix).
If x < y, you end up outside of the memory you allocated.
If x > y, you end up with uninitialized pointers.
So change it as follows
for (int i = 0; i < x; i++) {
matrix[i] = (numeric*)malloc(y * sizeof(numeric));
After these corrections try executing the code, you should get the expected results without any segfault errors
Here is the complete working code
#include <stdio.h> // Standard input output library
#include <math.h> // Mathematical function library
#include <stdlib.h> // General purpose standard library
#define true 1
#define false 0
typedef long double numeric; // Using the long double datatype to avoid overflows during computations
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//----------------------------------------------------------------FUNCTION DECLERATION-------------------------------------------------------------//
numeric **create_matrix(int x, int y); // To dynamically allocate memory and create a matrix
void input_matrix(numeric **matrix, int m, int n); // To accept a matrix
void print_matrix(numeric **l, int x, int y); // To print a matrix
numeric **standard_matrix_multiplication(int m, int n, int l); // To multiply two matrices
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//------------------------------------------------------------------DRIVER CODE--------------------------------------------------------------------//
int main(int argc, char *argv[]) {
int m, n, l; int choice;
printf("Enter the matrix operation to be performed using the corresponding index number.\n");
printf("\n");
printf("1.\tMatrix Multiplication");
printf("\n");
scanf("%d", &choice);
switch(choice) {
case 1 :
printf("Enter the number of rows in the first matrix\n");
scanf("%d", &m);
printf("Enter the number of columns in the first matrix\n");
scanf("%d", &n);
printf("Enter the number of columns in the second matrix\n");
scanf("%d", &l);
printf("Enter both matrices.\n");
numeric **matrix_x;
matrix_x = create_matrix(m, l);
matrix_x = standard_matrix_multiplication(m, n, l);
print_matrix(matrix_x, m, l);
break;
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//----------------------------------------------------------MATRIX MULTIPLICATION IMPLEMENTATIONS--------------------------------------------------//
numeric **standard_matrix_multiplication(int m, int n, int l) {
numeric **matrix_a; numeric **matrix_b; numeric **matrix_k;
matrix_a = create_matrix(m, n);
matrix_b = create_matrix(n, l);
matrix_k = create_matrix(m, l);
input_matrix(matrix_a, m, n);
print_matrix(matrix_a, m, n);
input_matrix(matrix_b, n, l);
//print_matrix(matrix_b, n, l);
for(int i = 0; i < m; i++) {
for (int j = 0; j < l; j ++) {
for (int k = 0; k < n; k++) {
matrix_k[i][j] += matrix_a[i][k] * matrix_b[k][j];
}
}
}
return matrix_k;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//---------------------------------------------------------------HELPER FUNCTIONS------------------------------------------------------------------//
numeric **create_matrix(int x, int y) {
numeric **matrix = (numeric**)malloc(x * sizeof(numeric*)); // Dynamically creating an array of pointers
for (int i = 0; i < x; i++) {
matrix[i] = (numeric*)malloc(y * sizeof(numeric)); // Dynamically allocating memory for each columns of the matrix
}
return matrix;
}
void input_matrix(numeric **matrix, int m, int n) {
printf("Enter the elements of the matrix, row wise.\n"); // Instructing the user on matrix entry
printf("For example, to enter the matrix\n");
printf("\t\t1\t2\n");
printf("\t\t3\t4\n");
printf("enter 1, 2, 3, and 4 in that order.\n");
for (int i = 0; i < m; i++) { // Iterating through the rows and columns of the matrix
for (int j = 0; j < n; j++) {
scanf("%Lf", &matrix[i][j]); // Accepting each element
}
}
}
void print_matrix(numeric **l, int x, int y) { // To print a matrix
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
printf("%0.10Lf\t", l[i][j]); // Printing numeric type values
}
printf("\n");
}
printf("\n");
}

You are not allocating enough memory for matrix_k. You are allocating memory for m rows and l columns, but you are trying to access m rows and n columns. You need to allocate memory for m rows and n columns. You can do this by changing the line
matrix_k = create_matrix(m, l);
to
matrix_k = create_matrix(m, n);
This is the same problem you had in your other question.

Related

Error when passing 2D array to function in c

I am writing a program to calculate matrix multiplication but it does not work. When I debug and check each value of the array a and b in function printMatrixMultiplication (which are entered by user), GDB prints out "cannot perform pointer math on incomplete type try casting". (I have searched for it but I still don't get it.) The function only works when the input is predefined in main.
This is my code
#include <stdio.h>
void input(int m, int n, double a[m][n]);
void output(int m, int n, double a[m][n]);
void printMatrixMultiplication(int row_a, int col_a, double a[row_a][col_a], int row_b, int col_b, double b[row_b][col_b]);
int main()
{
int row_a, col_a, row_b, col_b;
// get value of matrix a
printf("row_a = ");
scanf("%d", &row_a);
printf("col_a = ");
scanf("%d", &col_a);
double a[row_a][col_a];
input(row_a, col_a, a);
// output(row_a, col_a, a);
// get value of matrix b
printf("row_b = ");
scanf("%d", &row_b);
printf("col_b = ");
scanf("%d", &col_b);
double b[row_b][col_b];
input(row_b, col_b, a);
// output(row_b, col_b, a);
printMatrixMultiplication(row_a, col_a, a, row_b, col_b, b);
//test
// double a[2][2]={1,2,3,4};
// double b[2][3]={1,2,3,4,5,6};
// printMatrixMultiplication(2,2,a,2,3,b);
return 0;
}
void input(int m, int n, double a[m][n])
{
int i, j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
scanf("%lf", &a[i][j]);
}
}
}
void output(int m, int n, double a[m][n])
{
int i, j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("%.2f ", a[i][j]);
}
printf("\n");
}
}
void printMatrixMultiplication(int row_a, int col_a, double a[row_a][col_a], int row_b, int col_b, double b[row_b][col_b])
{
if (col_a != row_b)
{
return;
}
double res[row_a][col_b]; //this matrix store results
for (int i = 0; i < row_a; i++) //the values be stored line by line, this
{ //operation is controled by i and j loops.
for (int j = 0; j < col_b; j++) //the k loop helps calculate dot_product.
{
double dot_product = 0;
for (int k = 0; k < col_a; k++)
{
dot_product += a[i][k] * b[k][j]; //ERROR HERE
}
res[i][j] = dot_product;
}
}
output(row_a, col_b, res);
}
So, where does the error come from and how to fix it?
Irrelevant, but the function is not well implemented so if possible, I would really appreciate if anyone gives me a hint to improve it.
I am using GCC version 6.3.0.
It's typo in your code when reading matrix b.
Just replace:
input(row_b, col_b, a);
with
input(row_b, col_b, b);

matrix multiplied by a vector in C

I have a matrix[2][3], a vector[3] and I am computing the result of this with the below code which works perfectly fine.
My approach: Initialize a product matrix of size [3][2] to zero, perform the computation as in the function matrix_x_vector and extract the last row to get the final output(vector).
What I expect: Instead of using a product matrix of size [3][2] and then extracting the vector from it, is there any direct way of multiplying a matrix by a vector and store it directly into a resultant vector.
#include <stdio.h>
int main()
{
// Define Variables
int n1 = 2, n2= 3;
int vector[3] = {2,1,2};
int matrix[2][3] = {
{1,-1,2},
{2,-3,1},
};
int Product_matrix[3][2] = {
{0},
{0},
{0}
};
// Define Functions
void matrix_x_vector(int n1,int n2, int vector[n2], int matrix[n1][n2], int Product[n1][n2]); // Performs the calculation
// Execute Functions
matrix_x_vector(n1, n2, vector, matrix, Product_matrix);
printf("\n");
return 0;
}
void matrix_x_vector(int n1,int n2, int vector[n2], int matrix[n1][n2], int Product[n1][n2])
{
int i, j; // i = row; j = column;
printf("\nProduct Matrix of [x]*[y]\n");
// Load up A[n][n]
for (i=0; i<n2; i++)
{
for (j=0; j<n1; j++)
{
Product[j][0] += matrix[j][i] * vector[i];
printf("%4i", Product[j][0]);
}
printf("\n");
}
printf("Vector: \n");
// Print Vector from Product[n][n]
for (i=0; i<n1; i++){
printf("%4i\n", Product[i][0]);
}
}
Product Matrix of [x]*[y]
2 4
1 1
5 3
Vector:
5
3
If I understood the question correctly, it is asked for a function which uses a vector instead of a matrix for the result type. This function can be formulated as follows.
void matrix_x_vector_new(int n1,
int n2,
int vector[3],
int matrix[2][3],
int result_vector[3])
{
int i, j; // i = row; j = column;
printf("\nProduct Matrix of [x]*[y]\n");
// Load up A[n][n]
for (i = 0; i<n2; i++)
{
for (j = 0; j<n1; j++)
{
result_vector[j] += matrix[j][i] * vector[i];
printf("%4i", result_vector[j]);
}
printf("\n");
}
printf("Vector: \n");
// Print Vector from Product[n][n]
for (i = 0; i<n1; i++)
{
printf("%4i\n", result_vector[i]);
}
}

How to add integers in from two 2d arrays into a new 2d array with specified length by user?

I am fairly new around here and this year is the first time I am learning c. I have run into a problem concerning 2D arrays and such. The question is: Write a program that finds the sum of two 2D matrixes.
I can do this fairly easily but there is a problem I'm running into. For example I'll give the first set of arrays a length of 3x3.
If my first 2D array and the second array has:
{1,2,3; 4,5,6; 7,8,9} (1st array)
{0,0,0; 0,0,0; 0,0,0} (2nd array)
I am also given a the number of rows and columns by user. (User inputs 3x2) then it should appear like
{1,2; 3,4; 5,6} (OUTPUT)
but I am getting
{1,2; 3,5; 6,8}
Another example
User inputs 2x4 OUTPUT should be {1,2,3,4; 5,6,7,8}
What am I doing wrong here?
#include <stdio.h>
#include <stdlib.h>
#define MAXROW 3
#define MAXCOL 3
int main() {
int ray1[MAXROW][MAXCOL], ray2[MAXROW][MAXCOL];
int r, c;
printf("Enter the number of ROWS: ");
scanf("%d", &r);
printf("Enter the number of COLUMNS: ");
scanf("%d", &c);
int sumRay[r][c];
printf("\n");
printf("Input integers for Array %d.\n", 1);
arrayIN(ray1);
printRay(ray1);
printf("Input integers for Array %d.\n", 2);
arrayIN(ray2);
printRay(ray2);
arraySUM(ray1, ray2, r, c, sumRay);
printSumRay(r, c, sumRay);
//printRay(sumRay);
}
void arrayIN(int ray[MAXROW][MAXCOL]) {
int r, c;
for (r = 0; r < MAXROW; r++) {
for (c = 0; c < MAXCOL; c++) {
printf("Enter Number for [ROW:%d COL:%d]: ", r, c);
scanf("%d", &ray[r][c]);
}
}
}
void arraySUM(int ray1[MAXROW][MAXCOL], int ray2[MAXROW][MAXCOL],
int r, int c, int sumRay[r][c]) {
int i, j;
int x, y;
i = j = 0;
int sum;
for (x = 0; x <= r; x++, i++) {
if (i < MAXROW) {
for (y = 0; y <= c; y++, j++) {
if (j < MAXCOL) {
sum = ray1[i][j] + ray2[i][j];
sumRay[x][y]= sum;
} else {
j = 0;
}
}
} else {
i = 0;
}
}
printf("\n");
}
void printSumRay(int r, int c, int sumRay[r][c]) {
int i, j;
for (i = 0; i < r; i++) {
printf("\n");
for (j = 0; j < c; j++) {
printf("%d\t", sumRay[i][j]);
}
}
}
void printRay(int ray[MAXROW][MAXCOL]) {
int i, j;
for (i = 0; i < 3; i++) {
printf("\n");
for (j = 0; j < 3; j++) {
printf("%d\t", ray[i][j]);
}
}
printf("\n");
}
First off, you need to put function prototypes before main(), or at least move the function definitions before main(). It is not at all clear to me why you use a VLA for sumRay[][], but arrays of constant dimensions for ray1[][] and ray2[][]. Unless you have a compelling reason for doing so, it will be better to use VLA's all around.
You should be using the size_t type for variables that hold array indices. The scanf() and printf() statements that handle the size_t variables must then be modified to use the %zu conversion specifier.
The arraySum() function iterates over two pairs of duplicate array indices for reasons which are unclear. The logic here is convoluted and overly complex. The spurious output that you reported can be traced to this function; it is difficult to read and understand, which should be a sign that it needs to be rewritten. And if your intention is to add the input arrays only partially, the name does not reflect this intention. I have simplified this function, tightening the logic and removing the duplications. See the update below for a version that does partial array addition.
The printSumRay() function seems superfluous, since the printRay() function can do the same work, so I removed it, rewriting printRay() to use VLA's and tightening the code. The original code was using the magic number 3 in the controlling expressions of the loops here, instead of taking advantage of MAXROW and MAXCOL. But, even when not using VLA's, it is better practice to pass the dimensions to any function that will work with an array.
Here is a modified version of the original code:
#include <stdio.h>
#include <stdlib.h>
void arrayIN(size_t r, size_t c, int ray[r][c]);
void arraySUM(size_t r, size_t c, int ray1[r][c], int ray2[r][c], int sumRay[r][c]);
void printRay(size_t r, size_t c, int ray[r][c]);
int main(void)
{
size_t r,c;
printf("Enter the number of ROWS: ");
scanf("%zu", &r);
printf("Enter the number of COLUMNS: ");
scanf("%zu", &c);
int ray1[r][c], ray2[r][c], sumRay[r][c];
printf("\n");
printf("Input integers for Array %d.\n", 1);
arrayIN(r, c, ray1);
putchar('\n');
printRay(r, c, ray1);
putchar('\n');
printf("Input integers for Array %d.\n", 2);
arrayIN(r, c, ray2);
putchar('\n');
printRay(r, c, ray2);
putchar('\n');
arraySUM(r, c, ray1, ray2, sumRay);
printRay(r, c, sumRay);
putchar('\n');
return 0;
}
void arrayIN(size_t r, size_t c, int ray[r][c])
{
for(size_t i = 0; i < r; i++) {
for(size_t j = 0; j < c; j++) {
printf("Enter Number for [ROW:%zu COL:%zu]: ", i, j);
scanf("%d", &ray[i][j]);
}
}
}
void arraySUM(size_t r, size_t c, int ray1[r][c],int ray2[r][c], int sumRay[r][c])
{
for(size_t i = 0; i < r; i++) {
for(size_t j = 0; j < c; j++) {
sumRay[i][j] = ray1[i][j] + ray2[i][j];
}
}
}
void printRay(size_t r, size_t c, int ray[r][c])
{
for(size_t i = 0; i < r; i++) {
for(size_t j = 0; j < c; j++) {
printf("%8d",ray[i][j]);
}
putchar('\n');
}
}
As a next step, you might add some error-checking to the input code, checking the return values from the calls to scanf(). And, as it is, it is awkward to enter the numbers for the arrays, being prompted for each element. You might experiment with ways to improve this.
Update
If your true goal is to combine only the initial rows and columns of your arrays, the above code works with only minor modification. You should still use VLAs, but instead of defining the global constants MAXROW and MAXCOL, define const size_t maxrow and const size_t maxcol within the body of main(). You should be passing these array dimensions to the functions anyway, not relying on global values.
A function has been added, partArraySUM(), with a name that more closely captures its purpose. The only difference between this function and arraySUM() is that the input arrays ray1[][] and ray2[][] have different dimensions than the array sumRay[][] which holds the results. There is no need to keep separate indices for this.
#include <stdio.h>
#include <stdlib.h>
void arrayIN(size_t r, size_t c, int ray[r][c]);
void arraySUM(size_t r, size_t c, int ray1[r][c], int ray2[r][c], int sumRay[r][c]);
void partArraySUM(size_t r_sz, size_t c_sz, int ray1[r_sz][c_sz], int ray2[r_sz][c_sz], size_t r, size_t c, int sumRay[r][c]);
void printRay(size_t r, size_t c, int ray[r][c]);
int main(void)
{
const size_t maxrow = 3;
const size_t maxcol = 3;
size_t r,c;
printf("Enter the number of ROWS: ");
scanf("%zu", &r);
printf("Enter the number of COLUMNS: ");
scanf("%zu", &c);
int ray1[maxrow][maxcol], ray2[maxrow][maxcol], sumRay[r][c];
printf("\n");
printf("Input integers for Array %d.\n", 1);
arrayIN(maxrow, maxcol, ray1);
putchar('\n');
printRay(maxrow, maxcol, ray1);
putchar('\n');
printf("Input integers for Array %d.\n", 2);
arrayIN(maxrow, maxcol, ray2);
putchar('\n');
printRay(maxrow, maxcol, ray2);
putchar('\n');
partArraySUM(maxrow, maxcol, ray1, ray2, r, c, sumRay);
printRay(r, c, sumRay);
putchar('\n');
return 0;
}
void arrayIN(size_t r, size_t c, int ray[r][c])
{
for(size_t i = 0; i < r; i++) {
for(size_t j = 0; j < c; j++) {
printf("Enter Number for [ROW:%zu COL:%zu]: ", i, j);
scanf("%d", &ray[i][j]);
}
}
}
void arraySUM(size_t r, size_t c, int ray1[r][c],int ray2[r][c], int sumRay[r][c])
{
for(size_t i = 0; i < r; i++) {
for(size_t j = 0; j < c; j++) {
sumRay[i][j] = ray1[i][j] + ray2[i][j];
}
}
}
void partArraySUM(size_t r_sz, size_t c_sz, int ray1[r_sz][c_sz], int ray2[r_sz][c_sz], size_t r, size_t c, int sumRay[r][c])
{
for(size_t i = 0; i < r; i++) {
for(size_t j = 0; j < c; j++) {
sumRay[i][j] = ray1[i][j] + ray2[i][j];
}
}
}
void printRay(size_t r, size_t c, int ray[r][c])
{
for(size_t i = 0; i < r; i++) {
for(size_t j = 0; j < c; j++) {
printf("%8d",ray[i][j]);
}
putchar('\n');
}
}
Sample interaction:
Enter the number of ROWS: 2
Enter the number of COLUMNS: 2
Input integers for Array 1.
Enter Number for [ROW:0 COL:0]: 1
Enter Number for [ROW:0 COL:1]: 2
Enter Number for [ROW:0 COL:2]: 3
Enter Number for [ROW:1 COL:0]: 4
Enter Number for [ROW:1 COL:1]: 5
Enter Number for [ROW:1 COL:2]: 6
Enter Number for [ROW:2 COL:0]: 7
Enter Number for [ROW:2 COL:1]: 8
Enter Number for [ROW:2 COL:2]: 9
1 2 3
4 5 6
7 8 9
Input integers for Array 2.
Enter Number for [ROW:0 COL:0]: 1
Enter Number for [ROW:0 COL:1]: 1
Enter Number for [ROW:0 COL:2]: 1
Enter Number for [ROW:1 COL:0]: 1
Enter Number for [ROW:1 COL:1]: 1
Enter Number for [ROW:1 COL:2]: 1
Enter Number for [ROW:2 COL:0]: 1
Enter Number for [ROW:2 COL:1]: 1
Enter Number for [ROW:2 COL:2]: 1
1 1 1
1 1 1
1 1 1
2 3
5 6
Just a minor change is needed. In arraySUM(), inside the else part you have re initialized
i=0 and j=0.
But after the re initialization they are incremented. So it will become 1 so while execution it will read ray[1], not ray[0].
Just re initialize them to -1.
i=-1 and j=-1

Recursive function calculating average from int array three by three elements

Calculating average three by three elements and replacing those elements with the average result.
Example array [1,2,7,-2,5,0, 2,8]
After transformation [3,3,3,1,1,1,5,5]
Something is wrong, I can't get it to work.
#include <stdio.h>
int main ( ) {
int n, c[n];
int *avg;
int pom=0;
printf("Enter lenght of array\n");
scanf("%d",&n);
printf("Enter elements");
for(i = 0;i < n; i++)
scanf("%d",c[i]);
avg=Average(c , n, pom);
for(i = 0; i < n; i++)
printf("Avg elements= %d",*(avg+i))
return 0;
}
int Average(int arr[], int size, int z)
{
int k, l, m, Asum;
if (size < 0) {
return arr;
} else {
k=arr[z];
l=arr[z+1];
m=arr[z+2];
Asum=(k + l + m)/3;
arr[z]=Asum;
arr[z+1]=Asum;
arr[z+2]=Asum;
}
return Average(arr,size--,z++);
}
int n, c[n]; is a problem. n is uninitialized so the size of the array is who-knows-what? This is undefined behavior.
Instead
int main(void) {
int n;
int *avg;
int pom=0;
printf("Enter length of array\n");
if (scanf("%d",&n) != 1) return -1;
int c[n];
for(i = 0;i < n; i++)
// scanf("%d",c[i]);
scanf("%d",&c[i]); // pass the address of an `int`
Likely other issues too.
Try simple input first, imagine what happens when you enter only 1 number, what will the Average function do? Don't run the code but try to execute it in your head or with pencil and paper. If you think the program only has to work with three or more numbers, try three.
A serious program would explicitly reject invalid input.

How to create a 2d array, the dimensions of which are specified by the user? (in C)

Here is my try. I am not totally sure about my manipulations with the pointer. Maybe this is why I am wrong, maybe there is some other case. I want to take the dimensions from the user and create a square matrix, make some manipulations with its elements, and display the original and results to the user. Last time I accomplished this by creating a 100x100 array, and specifying the end of each line, and end of lines by constants. Then I would print all the elements up to this constant. But it does not seem to be right to create a 100x100 array for 4x4 matrices. I could create a smaller array, but this does not seem to be the right solution to the problem. Is there a way in C to create a 2d array exactly the size specified by the users (it will be a square array). Thanks
#include <stdio.h>
#include <stdlib.h>
double * createMatrix(int dimentions);
void drawMatrix(double * matrix);
int main(void)
{
int n, i, j;
system("cls");
system("color 70");
system("pause");
puts("Enter the matrix's dimension");
scanf("%i", &n);
double * pmatrix = createMatrix(n);
for (i = 0; i < n; ++j)
for (j = 0; j < n; ++j)
{
printf("A%i%i: ", i + 1, j + 1);
scanf("%lf", pmatrix[i][j]);
getchar();
}
for (i = 0; i < n; ++i)
{
putchar('\n');
for (j = 0; j < n; ++j)
printf(" %lf ", &pmatrix[i][j]);
}
system("color 08");
return 0;
}
double * createMatrix(int n)
{
const int N = n;
const int N1 = N;
double matrix[N][N];
double * pmatrix = matrix;
return pmatrix;
}
You can create a matrix directly; you don't need a function for that. Replace the code
double * pmatrix = createMatrix(n);
by the regular way of declaring a 2-D array:
double matrix[n][n];
One more way of doing it using pointers.
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
double **pmatrix;
int rowsize, colsize, i, j;
printf("Enter the number of rows: ");
scanf("%d",&rowsize);
printf("Enter the number of columns: ");
scanf("%d",&colsize);
//Allocate memory for 2D array
pmatrix = malloc(rowsize*sizeof(double*));
for(i=0;i<rowsize;i++)
{
pmatrix[i] = malloc(colsize*sizeof(int));
}
//Accepting the values
for(i=0;i<rowsize;i++)
{
for(j=0;j<colsize;j++)
{
printf("A %i %i: ", i + 1, j + 1);
scanf("%lf",&pmatrix[i][j]);
}
}
//Printing the values
for(i=0;i<rowsize;i++)
{
for(j=0;j<colsize;j++)
{
printf("%lf\t",pmatrix[i][j]);
}
printf("\n");
}
//Free the memory
for(i=0;i<rowsize;i++)
free(pmatrix[i]);
free(pmatrix);
return 0;
}

Resources