I need to create a matrix calculator, for that I think the best is to create functions for +,-,*,/.
But a lot of troubles come with this idea.
I create a calloced array like:
int **matrix = NULL;
matrix=calloc(cols,sizeof(int*));
for(int i=0;i<cols;i++) {
matrix[i]=calloc(rows,sizeof(int*));
}
For now I want to create a function where I want to work with this array.
void addition(int **array,int rows, int cols){
// ** some algoritm here**
return (the result of addition stored in 2D array);
}
I also tried to google the problem, but I didn't underestand the solutions. What I need to explain the way how to pass the array to function, just for reading.
After that I need to return some pointer to new array created as the result of addition. I will probably create the new array in the function.
But If I wanted to write something in array created in main, how to pass and use it in the function?
Related
I have school assignment which consists in creating a program that does math operation with Matrix. In this program, I have to create Matrix using typedef.
This typedef should hold 4 x 4 Matrix with double type.
So for this here is my implementation:
typedef struct {
char * name;
double * data;
int elements;
} mat;
In main, I need to define several mat objects this way:
mat MAT_A, MAT_B, MAT_C, MAT_D, MAT_E, MAT_F;
And this user should type its input for example: add_mat mat_a,mat_b,mat_c,
this operation will add 2 Matrix mat_a and mat_b into mat_c.
So after that this user input and split it with Comma\Tab, I want to write simple function that gets a char which is the required mat and returns the relevant mat:
For example:
mat getmatrix(char name, mat *mats)
{
int i;
for (i = 0; i < 6; i++)
{
if (strcmp(mats[i].name, "MAT_A") == 0)
{
return mats[i];
}
}
.....
}
For this, I insert all my mat objects into array:
mat mats[] = { MAT_A, MAT_B, MAT_C, MAT_D, MAT_E, MAT_F };
But I get this error for all my mat objects:
uninitialized local variable 'MAT_A' used
Any suggestions on how to fix it or maybe find another way to read the input?
The way you write it, mats would contain copies of MAT_A etc. This is not what you want.
Your getmatrix function also returns a copy of a matrix. You don't really need it (and copying structs that contain pointers is dangerous; but see below). You probably want to return the matrix by pointer, and also accept matrix parameters in all functions by pointer.
I suggest getting rid of MAT_A and friends as you don't really need them. Use only mats[i]. You need to specify the number of elements in mats:
mat mats[10];
Don't forget to initialise mats properly.
If for some ungodly reason you are required to define 10 or so different variables of type mat, you need to change mats to be an array of pointers (yes the common theme here is pointers, you have to use them everywhere).
mat* mats[] = { &MAT_A, &MAT_B, /* etc */ };
Change getmatrix accordingly.
Another thing to consider: if your matrix dimension is fixed, you are using pointers with no reason. Declaring double data[4][4] will simplify things considerably. Same thing about name, consider making it a fixed-size character array.
I have a matrix M[2][2] and want to make a call to function dontModify(M) that will play around with the elements of M but not change them. Something like:
dontModify(M):
swap off-diagonal elements;
take determinant of M;
return determinant;
...but without having the function change M in the process. Anything convenient that would accomplish this?
Create a local copy of the matrix inside the function, one that you can do whatever you want with.
int some_function(int matrix[2][2])
{
int local_matrix[2][2] = {
{ matrix[0][0], matrix[0][1] },
{ matrix[1][0], matrix[1][1] },
};
/* Do things with `local_matrix` */
/* Do _not_ use `matrix` */
...
}
Frankly speaking do not undestand your problem. You are working with matrix, so it will be passing via pointer to function. So just create a copy of your matrix, play with it, destroy the copy before returning back. In case this call will be very frequent, you can try to save some time and just work in-place, just do not forget to swap off-diagonal elements back before return.
can i do some calculation using the sizeof operator in c to get
the rows count inside a function who receives as a parameter only
a two dimensional array without any information about rows or columns count in this passed array?
void main(void){
int A[5][6];
int columnsC = sizeof(A[0]) / sizeof(int);
int rowsC = ( sizeof(A)/sizeof(int) ) / columnsC;
printf("rows: %d\ncolumns: %d\n", rowsC, columnsC);
getch();
}
the previous code worked for me, but i can't find a helpful resource to know how to apply this on a function of the following header:
void fun(int arr[][10])
i"m studying a course on Programming Languages Principles, and some times think of things differently and look for learning resources, and this helps a lot, but not this time apparently.
i admire any help.
No. There's no way find the size of an array when passed to a function. Array decays into a pointer when passed to a function.
This:
void fun(int arr[][10])
is actually syntatic sugar for:
void fun(int (*arr)[10])
Instead you can pass the size as a thrid argument or size as an element of the array itself.
I do not believe this is possible, unless you either pass a length, or you specifically allocate one extra row to the array. This extra row can contain a null character. In the function fun, then you can use a while loop to cycle through the array until you hit the null value.
int i = 0;
while (1) {
if(arr[i]==NULL){
//exits when hits end
break;
}
//do stuff with arr[i]
i++;
}
I have an array, which is now static. This are the operations I do with it.
Firstly I create a two-dimensional array. Then I fill it in, using cycles. And then I send it to function, where there are also cycles which are used.
Here I 'd like to post some sample code, which is similar to mine.
bool picture[20][20]; //here's my array right now. Pretty ugly. Just for testing.
for (int y=0;y<Height;y++)
{
for (int x=0;x<Width;x++)
{
if (treshold<middle)
{
picture[x][y]=1;
}
else
{
picture[x][y]=0;
}
}
}
//Here's an example of filling an array
leftk = left(picture,widthk, heightk); //That's how I use a function
int left(int picture[200][200],int row,int col)
{
for (int x = 0; x <=row-1; x++)
{
for (int y = 0; y <=col-1 ;y++)
{
if (picture1[x][y]==1)
{
return x;
}
}
}
}
//And that's the function itself
So here I need to switch my array to a dynamic one. That's how I declare my dynamic array
bool** picture=new bool*[size];
for(int i = 0; i < size; ++i)
picture[i] = new bool[size];
//size is just a variable.
As for statically declared cycles, everything is very simple. Sending this array as a parameter to function.
I've already managed to create a dynamic array, it's simple. Then I fill it in with numbers. No problems here too. But I can't understand, how to send an array to function and moreover how to use it there.
Could you give me an exaple of modifying two-dimensional arrays in functions.
Sorry for such a newbie question. Hope someone will help.
By the way, class wrapping would be a bit confusing here, I think.
A function such as:
Process2DArray(int **pArray, int rowCount, int colCount)
Should suffice the needs assuming its a 2D array that is being operated on. Also, consider using std::vector<std::vector<int>> instead of a multidimensional array allocated manually. This approach will help prevent leaks. The second approach also lets you have jagged arrays.
The usual solution is to wrap the array in a class; C doesn't handle
arrays very well, and C++ doesn't have any real support for 2D arrays in
its library either. So you define either:
class Array2D
{
std::vector<double> myData;
int myColumnCount;
int myRowCound;
// ...
};
with accessors which convert the two indexes using i * myColumnCount +
j, or:
class Array2D
{
std::vector<std::vector<double> > myData;
// ...
};
with initialization logic ensure that all of the rows have the same
length. The first is generally simpler and easier to understand; if you
want to increase the number of columns, however, the second is
significantly easier.
You have several options:
an array of arrays. For example, for int would be int **a which should be able to hold n arrays new int *[n], then go with a for through them and initialized them a[i] = new int[elems_per_line]
a "packed" 1D array int *a = new int[n * elems_per_line], where element (i, j) - 0-based is actually a[i * elems_per_line + j].
you can refine point 1, and have the 2D matrix be "curly" - with lines of different lengths, but you'll need an array to hold each length.
Hope this helps.
I'm facing some trouble to find the best way to return an struct with an array or pointer to an array.
here is what i want to do:
i have a struct
typedef struct {
double *matrix;
int cols;
int rows;
int nelems;
} ResultMat;
and a function that parses a file. I need to call that function and have it return the struct
ResultMat read (string file, string tag) {
ResultMat mat;
.....
mat.cols = //some value from the file
mat.rows = //some value from the file
double array[rows][cols];
//now i fill the array
.......
mat.matrix = *array;
return mat;
}
within an array is filled with the values and i want to get back that whole struct with the
array/ pointer to the array stored in mat.matrix.
How to do that and is there maybe a better way? Im quite new to C and more familiar with OO programming, thats why I'm having trouble to find the best solution.
Hope anybody can give me some help! Thanks
I think that
double array[rows][cols];
will be a problem, as you create the array on the local function stack.
This will be erased once you leave the function.
You should also be aware of, that Variable-Length arrays are not ANSI-C conform and you should better not use it in my opinion.
You should work with pointers and dynamic memory allocation.
malloc would be the keyword here.
Hope this helps
The only other way I can think of, is to put all the output arguments as input pointers so that your prototype function would look like this:
void read (string file, string tag, double *matrix, int *cols, int *rows, int *nelms);
or you can keep the structure and go for something like this:
void read (string file, string tag, ResultMat *myStructure);
IMO, there is no "better way", these are all just different options, yours is another option, which I found myself using very often.