How to return matrix? - c

I'm trying to make a Cramer-linear-solving, and I wrote a function that replaces a matrix column, just like that:
void replacecol(int c, int n, float mat_in[n][n], float vect_in[n],
float mat_out[n][n])
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (j == c)
{
mat_out[i][j] = vect_in[j];
}
else
{
mat_out[i][j] = mat_in[i][j];
}
}
}
}
But it is currently void, and I want it to return the mat_out with it's values, when I call this function... How could I do that??

You can avoid to use 2 matrices for your function. You can simply:
void replacecol(int c, int n, float mat_in[n][n], float vect_in[n]))
{
int i;
for (i = 0; i < n; i++)
{
mat_in[i][c] = vect_in[i];
}
}
float mat_in[n][c] it is a pointer float(*)[] so modifications on that parameter are made on the passed matrix.

Related

how to scan a 2d array using a function without deleting it's content

as a homework assignment, i need to scan N matrices and a user input integer, and scan if any of the matrices values contains that number
without using pointers.
as soon as i finish scanning the array and exits the function, the content of the array resets to zero, or trash if i dont init the array.
#pragma warning(disable:4996)
#include<stdio.h>
#define N 2
int exist(int matrix[][N], int elem);
void input_matrix(int matrix[][N], int size);
void main()
{
int matrix_1[][N] = { 0 }, matrix_2[][N] = { 0 }, matrix_3[][N] = { 0 };
int elem;
printf("please enter values of squared matrix:\n");
input_matrix(matrix_1[][N], N);
//(input_matrix(&matrix_2[N][N]));
// (input_matrix(&matrix_3[N][N]));
printf("please enter number to search for in the matrix:\n");
scanf("%d", &elem);
if (exist(matrix_1,elem))
//printf("exist.");//the next part of h.w to be written when input func works
}
void input_matrix(int matrix[][N], int size)//something here fishy
{
int i, j;
for (i = 0; i < size; i++)
{
for (j = 0; j < size; j++)
{
scanf("%d", &matrix[i][j]);
}
}
}
int exist(int matrix[][N], int elem)
{
int i, j;
int flag = 0;
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
if ((matrix[i][j]) == elem)
{
flag = 1;
break;
}
}
}
return flag;
}
Inside the main function, in the call input_matrix(matrix_1[][N], N) you pass the invalid parameter. Instead should pass the whole matrix, like input_matrix(matrix_1, N).
As noted in a comment, it will be better to declare matrix like matrix_1[N][N].

Create 2D array by passing pointer to function in c

So I read dozens of examples of passing an 2D array pointer to function to get/change values of that array in function. But is it possible to create (allocate memory) inside the function. Something like this:
#include <stdio.h>
void createArr(int** arrPtr, int x, int y);
int main() {
int x, y; //Dimension
int i, j; //Loop indexes
int** arr; //2D array pointer
arr = NULL;
x=3;
y=4;
createArr(arr, x, y);
for (i = 0; i < x; ++i) {
for (j = 0; j < y; ++j) {
printf("%d\n", arr[i][j]);
}
printf("\n");
}
_getch();
}
void createArr(int** arrPtr, int x, int y) {
int i, j; //Loop indexes
arrPtr = malloc(x*sizeof(int*));
for (i = 0; i < x; ++i)
arrPtr[i] = malloc(y*sizeof(int));
for (i = 0; i < x; ++i) {
for (j = 0; j < y; ++j) {
arrPtr[i][j] = i + j;
}
}
}
Forget about pointer-to-pointers. They have nothing to do with 2D arrays.
How to do it correctly: How do I correctly set up, access, and free a multidimensional array in C?.
One of many reasons why it is wrong to use pointer-to-pointer: Why do I need to use type** to point to type*?.
Example of how you could do it properly:
#include <stdio.h>
#include <stdlib.h>
void* create_2D_array (size_t x, size_t y)
{
int (*array)[y] = malloc( sizeof(int[x][y]) );
for (size_t i = 0; i < x; ++i)
{
for (size_t j = 0; j < y; ++j)
{
array[i][j] = (int)(i + j);
}
}
return array;
}
void print_2D_array (size_t x, size_t y, int array[x][y])
{
for (size_t i = 0; i < x; ++i)
{
for (size_t j = 0; j < y; ++j)
{
printf("%d ", array[i][j]);
}
printf("\n");
}
}
int main (void)
{
size_t x = 5;
size_t y = 3;
int (*arr_2D)[y];
arr_2D = create_2D_array(x, y);
print_2D_array(x, y, arr_2D);
free(arr_2D);
return 0;
}
Yes, passing a pointer to int ** (but 3 stars is considered bad style), I suggest to return an allocated variable from your function:
int **createArr(int x, int y)
{
int **arrPtr;
int i, j; //Loop indexes
arrPtr = malloc(x*sizeof(int*));
if (arrPtr == NULL) { /* always check the return of malloc */
perror("malloc");
exit(EXIT_FAILURE);
}
for (i = 0; i < x; ++i) {
arrPtr[i] = malloc(y*sizeof(int));
if (arrPtr[i] == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
}
for (i = 0; i < x; ++i) {
for (j = 0; j < y; ++j) {
arrPtr[i][j] = i + j;
}
}
return arrPtr;
}
Call it using:
arr = createArr(x, y);
Yes, an array can be initialized this way. As long as you pass a pointer, the memory address should remain the same. So, if you assign anything to the pointer it will valid.
Think of an a[] as a* pointer to the first element
a [][] will be a** pointer to a pointer of the first element or a pointer to the first array (first row of a table)

Creating a matrix in a structure

I am trying to create a structure that will have two integer values, an array, and two 2-D matrices using my code below. I can initialize the structure with the integers and array just fine, and my 'Gen' function will create the random values I want for the array.
However, when I try adding in the matrix components, I run into a problem. My compiler gives me a warning: "initialization from incompatible pointer type". If I understand what I have read so far, this is because the structure needs to be pointed to an array of pointers that represent each row in the matrix. I don't know the syntax for that.
A quick note: the other topics I've seen that are related to this issue all initialize the structure in a function other than the main() function, so I haven't found those solutions helpful.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include <string.h>
// Define structure
typedef struct {
int row;
int col;
int *arr;
int **mat1;
int **mat2;
}container;
// Function headers
void Gen(container Thing);
int main() {
int row = 5;
int col = 6;
int A[row];
int M1[row][col];
int M2[row][col+1];
// Initialize structure
container Object = {row, col, A, M1, M2};
// Run "Gen" function
Gen(Object);
int i, j; // Index variables
// Display the array
for(i = 0; i < row; i++)
{
printf("%i ", Object.arr[i]);
}
printf("\n\n");
// Display the numbers from the matrices
for(j = 0; j < Object.row; j++)
{
for(i = 0; i < Object.col; i++)
{
printf("%i ", Object.mat1[j][i]);
}
printf("\n");
}
printf("\n");
for(j = 0; j < Object.row; j++)
{
for(i = 0; i < Object.col; i++)
{
printf("%i ", Object.mat2[j][i]);
}
printf("\n");
}
return (EXIT_SUCCESS);
}
// Function to generate random values in the array & matrices
void Gen(container Thing)
{
int i, j;
srand(time(NULL));
// Generate random values for the array
for(i = 0; i < Thing.row; i++)
{
Thing.arr[i] = rand() % 5;
}
// Generate random values for the matrix
for(j = 0; j < Thing.row; j++)
{
for(i = 0; i < Thing.col; i++)
{
Thing.mat1[j][i] = rand() % 5;
Thing.mat2[j][i] = rand() % 5;
}
}
} // End of "Gen" function
container Object = {row, col, A, M1, M2};
is wrong since the type of M1 is int[row][col], which can decay to int (*)[col] but not to int**. You have the same problem with M2.
You'll need to rethink your strategy for generating a container.
For example:
int main() {
int row = 5;
int col = 6;
int A[row];
int* M1[row];
int* M2[row];
for ( int i = 0; i < row; ++i )
{
M1[i] = malloc(sizeof(M1[i][0])*col);
M2[i] = malloc(sizeof(M1[i][0])*(col+1));
}
// Initialize structure
container Object = {row, col, A, M1, M2};
...
for ( int i = 0; i < row; ++i )
{
free(M1[i]);
free(M2[i]);
}
return (EXIT_SUCCESS);
}

stack overflow unless printf under recursion

This code below is the code for finding the determinant for 3x3 matrix (this code is intended for nxn matrix, but for the sample, I used 3x3), using recursive
The result is working fine, but I wonder what errors in this code make this must be the printf("\n") before calling the sub-function (itself) or else it will return the error 0xc0000fd (stack overflow).
#include "stdio.h"
#include "stdlib.h"
#include "conio.h"
#define size 3
void trimarray(int**rrayrc,int**rrayout, int dim,int cuti,int cutj)
{
int i, j;
int ti = 0,tj;
for(i = 0; i<dim; i++)
{
tj = 0;
for(j = 0; j< dim; j++)
{
if(!((i==cuti)||(j==cutj)))
{
rrayout[ti][tj] = rrayrc[i][j];
}
if(j!=cutj) {tj++;}
}
if(i!=cuti) {ti++;}
}
}
void initializearray(int** rray,int dim)
{
int i, j;
for(i = 0; i<dim; i++)
{
for(j = 0; j<dim; j++)
{
rray[i][j] = 0;
}
}
}
int det(int** rray, int dim)
{
int i,j;
int cut[dim-1][dim-1];
int* cutp[i];
int mul = 1,sum=0;
if(dim >1)
{
for(i = 0; i<dim-1; i++)
{
cutp[i] = cut[i];
}
initializearray(cutp,dim-1);
for(i = 0; i<dim; i++)
{
printf("\n",dim); //<< Without this the program won't work
trimarray(rray,cutp,dim,0,i);
sum+=det(cutp,dim-1)*mul*rray[0][i];
mul = 0-mul;
}
return sum;
}
else
{
return rray[0][0];
}
}
int main()
{
int test[size][size] = {2,-3,-2,-6,3,3,-2,-3,-2};
int* testpntr[size];
int i,deter;
for(i = 0; i<size; i++)
{
testpntr[i] = test[i];
}
deter = det(testpntr,size);
printf("[%d]",deter);
getch();
return 0;
}
The answers will be dearly appreciated.
int* cutp[i]; is undefined behavior since i is uninitialized at this stage. You have no idea what is the size of cutp array.

compiler errors with multi dimensional arrays in c

This is the first time, when I'm using C. I have to do my numeric mathematics homework in C.
So I have problem using multi dimensional arrays. I don't now why I'm getting the following errors:
subscripted value is neither array nor pointer nor vector
subscripted value is neither array nor pointer nor vector
In function ‘inMatrix’:
error: subscripted value is neither array nor pointer nor vector|
In function ‘inVector’:|
error: subscripted value is neither array nor pointer nor vector|
In function ‘outVector’:|
error: subscripted value is neither array nor pointer nor vector|
In function ‘main’:|
error: incompatible type for argument 2 of ‘plu’|
note: expected ‘float (*)[(long unsigned int)(k)]’ but argument is of type ‘float’|
error: incompatible type for argument 3 of ‘plu’|
expected ‘float *’ but argument is of type ‘float’|
For example:
I don't know why it is complaining about the 'float *' when I didn't use a float pointer.Searching on google didn't return any results, so I don't know what the error is. I don't understand this error 'subscripted value is neither array nor pointer nor vector'.
What can I do? How can I rewrite my source code to get rid of these compiler errors?
Sorry for my poor English.
#include <stdio.h>
#include <stdlib.h>
void inMatrix(double matrix, int n)
{
int j, i;
for (i = 0; i < n; i++)
{
for (j= 0; j < n; j++)
{
scanf("%lf", &matrix[i][j]);
}
}
}
void inVector(double vektor, int n)
{
int k;
for (k = 0; k < n; k++)
{
scanf("%lf", &vektor[k]);
}
}
void outVector(double vektor, int n)
{
int k;
for (k = 0; k < n; k++)
{
printf("%.8lf", vektor[k]);
}
}
int plu(int k, float A[k][k], float b[k], float x[k])
{
int P[k];
int n, m, p, i, j;
int d=0;
int r=0;
int T=0;
float t=0;
float y[k];
//seged vektorok
for(n=1; n<k;n++)
{
x[n]=0;
y[n]=0;
}
// Permutaciós matrix
// permutation
for(i=1; i<k; i++)
{
P[i]=i;
}
// Rendezes
// sorting
for(d=1; d<k-1;d++)
{
p=0;
for(i=d; i<k; i++)
{
t=A[i][d];
if(t<0)
t=-1*t;
if(t>p)
{
p=t;
r=i;
}
}
//Ha szingularis
//If singular
if(p==0)
{
// printf("szingularis");
return 1;
}
//Matrix Csere
//Matrix change
T=P[r];
P[r]=P[d];
P[d]=T;
//matrix elem csere
//matrix value change
for(i=1; i<k; i++)
{
t=A[r][i];
A[r][i]=A[d][i];
A[d][i]=t;
}
for(i=d+1;i<k;i++)
{
A[i][d]=A[i][d]/A[d][d];
for(j=d+1; j<k; j++)
{
A[i][j]=A[i][j]-A[i][d]*A[d][j];
}
}
}
// Megoldas Vektorra
// Solve for Vector
for(n=1; n<k;n++)
{
t=0;
for(m=1;m<=n-1;m++)
{
t+=A[n][m]*y[m];
}
y[n]=b[P[n]]-t;
}
for(n=k-1;n>=1;n--)
{
t=0;
for(m=n+1; m<k;m++)
{
t+=A[n][m]*x[m];
}
x[n]=(y[n]-t)/A[n][n];
}
return 0;
}
int main()
{
//int i,j,k, num,value;
// d as numbers of dimmension
int d;
// Read dimension of array
scanf("%d", &d);
float matrix[d][d];
float vector[d];
inMatrix(matrix[d][d], d);
inVector(vector[d], d);
float resVector[d];
if(plu(d,matrix[d][d],vector[d], resVector[d])==1)
{
printf("szingularis");
}
else
{
outVector(resVector[d], d);
}
return 0;
}
Here, I've fixed the compiler errors for you.
I won't bother to explain in detail the errors as you clearly need to read a good book first.
#include <stdio.h>
#include <stdlib.h>
void inMatrix(int n,double matrix[n][n])
{
int j, i;
for (i = 0; i < n; i++)
{
for (j= 0; j < n; j++)
{
scanf("%lf", &matrix[i][j]);
}
}
}
void inVector(double vektor[], int n)
{
int k;
for (k = 0; k < n; k++)
{
scanf("%lf", &vektor[k]);
}
}
void outVector(double vektor[], int n)
{
int k;
for (k = 0; k < n; k++)
{
printf("%.8lf", vektor[k]);
}
}
int plu(int k, double A[k][k], double b[k], double x[k])
{
int P[k];
int n, m, p, i, j;
int d=0;
int r=0;
int T=0;
float t=0;
float y[k];
//seged vektorok
for(n=1; n<k;n++)
{
x[n]=0;
y[n]=0;
}
// Permutaciós matrix
// permutation
for(i=1; i<k; i++)
{
P[i]=i;
}
// Rendezes
// sorting
for(d=1; d<k-1;d++)
{
p=0;
for(i=d; i<k; i++)
{
t=A[i][d];
if(t<0)
t=-1*t;
if(t>p)
{
p=t;
r=i;
}
}
//Ha szingularis
//If singular
if(p==0)
{
// printf("szingularis");
return 1;
}
//Matrix Csere
//Matrix change
T=P[r];
P[r]=P[d];
P[d]=T;
//matrix elem csere
//matrix value change
for(i=1; i<k; i++)
{
t=A[r][i];
A[r][i]=A[d][i];
A[d][i]=t;
}
for(i=d+1;i<k;i++)
{
A[i][d]=A[i][d]/A[d][d];
for(j=d+1; j<k; j++)
{
A[i][j]=A[i][j]-A[i][d]*A[d][j];
}
}
}
// Megoldas Vektorra
// Solve for Vector
for(n=1; n<k;n++)
{
t=0;
for(m=1;m<=n-1;m++)
{
t+=A[n][m]*y[m];
}
y[n]=b[P[n]]-t;
}
for(n=k-1;n>=1;n--)
{
t=0;
for(m=n+1; m<k;m++)
{
t+=A[n][m]*x[m];
}
x[n]=(y[n]-t)/A[n][n];
}
return 0;
}
int main()
{
//int i,j,k, num,value;
// d as numbers of dimmension
int d;
// Read dimension of array
scanf("%d", &d);
double matrix[d][d];
double vector[d];
inMatrix(d,matrix);
inVector(vector, d);
double resVector[d];
if(plu(d,matrix,vector, resVector)==1)
{
printf("szingularis");
}
else
{
outVector(resVector, d);
}
return 0;
}
Your errors show that you don't understand the basics of C at all.
Take some time to review your concepts.
Well, I'm not totally clear on what your assignment was but lets look at the first function
I see you are trying to iterate through a square matrix of size n and read double-values from stdin into the matrix. The input parameter for this should not be (double, int). It should be (double*, int). A double* is an array of doubles. If you declare this function with just a double (like you did), then the program will allocate enough space for one double on the stack and your for-loop will be writing on important memory (and by that I mean it will most likely just crash) for array sizes bigger than one. Also, declaring it this way means the memory is found on the stack for this function call. This means that once the function is over, your array values you set are lost forever.
Instead, you need to declare it like:
void inMatrix(double* matrix, int n)
and pass in an array when you call it.
double myArray[16];
inMatrix(myArray, 4);
I hope this is helpful. Im not sure how much you understand about pointers/arrays.

Resources