Multidimensional arrays in functions in c - c

I have this exercise to make a transpose of a matrix in C. I made a function to check for type n*n but when I'm trying to ask the user for the matrix I don't know how I should declare the array. And I'm getting this compile error "type of formal parameter 1 is incomplete" in the function on the [n2] part.
The parameters of the functions for multi dimensional arrays shouldn't be like this -> int matrix[][n2]. or is cause i'm using a variable and not a constant or a pre defined size. ?
#include <stdio.h>
#define prompt "Dimenção da matriz (nxn) >>"
#define prompt_1 "Introduza os valores : "
void getType( int *n1, int *n2 );
void getMatrix( int matrix[][n2], int lim1, int lim2);
//void trans(int matrix[][n2]);
int main(int argc, char const *argv[]) {
int n1, n2;
getType(&n1, &n2);
int matrix[n1][n2];
//printf("%dx%d\n", n1, n2);
getMatrix(matrix, n1, n2);
//trans(matrix);
return 0;
}
void getType(int *n1, int *n2){
printf("%s", prompt );
scanf("%dx%d", &(*n1), &(*n2));
}
void getMatrix( int matrix[][n2], int lim1, int lim2){
printf("%s\n", prompt_1 );
for(int line = 0; line < lim1; line++ ){
for(int column = 0; column < lim2; column++){
printf("Linha %d coluna %d ->", line, column );
scanf("%d", &matrix[line][column]);
}
}
}

The signature should be:
void getMatrix( int lim1, int lim2, int matrix[lim1][lim2] )
You are allowed omit the lim1 inside square brackets but it is good documentation to include it.
The main point is that the variable inside the square brackets must either be a parameter from earlier in the parameter list, or some other variable in scope (which can only be a global variable, but that's usually a bad idea).
Also it would be good to check scanf return value otherwise you may create matrix with garbage dimension.

Related

After a pointer Returns from a function i cant print it

I am relatively new to C. My program is supposed to fill in the array with random numbers and i have to find the max and min using 1 function. The program works fine up until the point i have to return the values my 2 pointers get from the function. When i go to print them the porgram stop working and exits with the return value of 3221225477. I have been trying to fix this for 3 hours and i am going INSANE. Please help in any way you can i would really apreciate it.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void MaxMin(int size, int *B, int *Max, int *Min);
int main(int argc, char *argv[])
{
int N, i,*A,*MAX,*MIN;
srand(time(NULL));
/*Making sure the user enters a proper value for the array*/
do
{
printf("Give the number of spaces in the Array\n");
scanf("%d",&N);
}
while(N<1);
A = (int *) malloc(N*(sizeof(N)));
/*Giving random numbers to the array and printing them so i can make sure my code is finding the max min*/
for(i=0;i<N;i++)
{
A[i]=rand()%100;
printf("\n%d\n",A[i]);
}
/*Calling my void function so that the pointers MAX and MIN have a value assigned to them */
MaxMin(N, A, MAX, MIN);
/*Printing them*/
printf("\nMax = %d\nMin = %d",*MAX,*MIN);
free(A);
return 0;
}
/*The function*/
void MaxMin(int size, int *B, int *Max, int *Min)
{
/*using 2 temporary ints to get max min cause pointers and arrays confuse me*/
int max=B[0],min=B[0],i;
for(i=1;i<size;i++)
{
if(max<B[i])
{
max = B[i];
}
if(min>B[i])
{
min = B[i];
}
}
/*These have the proper value last i chekced */
Max = &max;
Min = &min;
}
(edit) SOLUTION Ty so much for the help !
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void MaxMin(int size, int *B, int *Max, int *Min);
int main(int argc, char *argv[])
{
int N, i,*A,MAX ,MIN ;
srand(time(NULL));
/*Making sure the user enters a proper value for the array*/
do
{
printf("Give the number of spaces in the Array\n");
scanf("%d",&N);
}
while(N<1);
A = (int *) malloc(N*(sizeof(int)));
/*Giving random numbers to the array and printing them so i can make sure my code is finding the max min*/
for(i=0;i<N;i++)
{
A[i]=rand()%100;
printf("\n%d\n",A[i]);
}
/*Calling my void function so that the pointers MAX and MIN have a value assigned to them */
MaxMin(N, A, &MAX, &MIN);
/*Printing them*/
printf("\nMax = %d\nMin = %d",MAX,MIN);
free(A);
return 0;
}
/*The function*/
void MaxMin(int size, int *B, int *Max, int *Min)
{
*Max=B[0];
*Min=B[0];
int i;
for(i=1;i<size;i++)
{
if(*Max<B[i])
{
*Max = B[i];
}
if(*Min>B[i])
{
*Min = B[i];
}
}
}
You passed to the function MaxMin pointers MAX and MIN by value. That is the function deals with copies of (indeterminate) values of the passed pointers. Changing the copies does not influence on the original arguments.
Within main you should declare MIN and MAX as objects of the type int.
int N, i,*A, MAX, MIN;
and call the function ,like
MaxMin(N, A, &MAX, &MIN);
Within the function you should write
*Max = &max;
*Min = &min;
And at last in main you should call printf like
printf("\nMax = %d\nMin = %d", MAX, MIN);
Pay attention to that the expression sizeof( N ) used in this statement
A = (int *) malloc(N*(sizeof(N)));
is error prone. The type of the variable N can be changed for example from the type int to the type size_t. In this case the size of the allocated memory will be incorrect, You should write for example
A = (int *) malloc(N*(sizeof( *A )));
You have three bugs:
In main, you don't assign MAX or MIN any values. So you pass garbage to MaxMin.
In MaxMin, Max and Min are about to go out of scope. Changing their values before they go out of scope has no effect on anything.
In main, you don't create any place to hold the maximum and minimum values. So where are you expecting them to be stored?

How do I pass in a 2d array I made from main into another function in C

so I'm trying to make a 2d binary matrix that is the size provided by stdin and that has randomly assigned indexes for the 0 and 1, however, their cannot be more than size/2 zeroes or ones.
For example
an input of 2
could output
1 0
0 1
Now I was going to originally just use the argument int arr[][n] in init but this idea failed since passing in the matrix just resulted in my program going on some sort of an infinite loop when I attempted to access matrix again inside of the main function. I believe this happened because the lifespan of matrix expired when init concluded? So my question here is why is what I'm doing now producing the below error and how can I fix this up?
note: expected ‘int * (*)[(sizetype)(n)]’ but argument is of type ‘int (*)[(sizetype)(dim)][(sizetype)(dim)]’
7 | int init(int n, int* arr[][n]);
My code
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int init(int n, int* arr[][n]);
int main(){
time_t t;
srand((unsigned) time(&t));
int dim;
printf("Enter a positive even integer: ");
scanf("%d",&dim);
if(dim<2||dim>80){
return 1;
}
int matrix[dim][dim];
init(dim,&matrix);
return 0;
}
int init(int n, int* arr[][n]){
int numZeroes,numOnes;
int zero_or_one;
for(int row=0;row<n;row++){
numZeroes=0;
numOnes=0;
for(int col=0;col<n;col++){
if(numZeroes<n/2 && numOnes<n/2){
zero_or_one=rand()%2;
*arr[row][col]=zero_or_one;
if(zero_or_one==1){
numOnes++;
}
if(zero_or_one==0){
numZeroes++;
}
}
else{
if(numZeroes==n/2 && numOnes<n/2){
*arr[row][col]=1;
}
if(numZeroes<n/2 && numOnes==n/2){
*arr[row][col]=0;
}
}
}
}
for(int row=0;row<n;row++){
for(int col=0;col<n;col++){
printf("%d ",*arr[row][col]);
}
printf("\n");
}
return 0;
}
The function should be declared like
void init(int n, int arr[][n]);
(the return type int of the function does not make a great sense.)
and called like
init(dim, matrix);
Within the function instead of statements like this
*arr[row][col]=zero_or_one;
you have to write
arr[row][col]=zero_or_one;

storage size of array isn't constant

i'm new to c. i'm writing a .h file dedicated to matrix. I want to write a function in .h file that returns a matrix (array) (not possible in c), so the real return is a pointer to a local array variable. But i can't use a local pointer in the main funct, so i've changed the int matrix[][] to static int matrix[][]. The problem now is: the user insert the number N of rows/columns, but a static array can only take a constant dimension. help
This is the .h
int N;
int i;
int j;
int *get_matrix(){
int user_input;
printf("set the dimension NxN of your matrix >> N=");
scanf("%d",&N );
static int temp_matrix[N][N];
for(i=0;i<N;i++){
for(j=0;j<N;j++){
printf("insert the matrix[%d][%d] value\n",i,j );
scanf("%d",&user_input);
temp_matrix[i][j]=user_input;
}
}
return temp_matrix;
}
void print_matrix(int *matrix){
for(i=0;i<sizeof(matrix)/4;i++){
for(j=0;j<sizeof(matrix)/4;j++){
printf("%7d",matrix[i][j]);
printf("\n");
}
}
}
this is the main.c file
#include <stdio.h>
#include "matrix_math.h"
void main(void){
int i;
int j;
int *p1 = get_matrix();
int matrix1[N][N];
for(i=0;i<N;i++){
for(j=0;j<N;j++){
matrix1[i][j]=p[i][j];
}
}
print_matrix(matrix1);
}
If this is just a school homework, and malloc not allowed/needed, and assuming it is acceptable to limit code to some reasonable upper limit N, consider defining matrix as a struct
#define MAXN 20
struct matrix {
int n ;
int data[MAXN][MAXN] ;
}
// matrix.c
struct matrix get_matrix() { ... ; return m } ;
void print_matrix(struct m *mp) {
for (int i = 0 ; i<mp->n ; i++) {
...
} ;
} ;
And then you can pass "matrix" around. Needless to say, better to pass matrix * whenever possible to improve performance. You can also make functions that return matrix, if needed.

Getting issues for redefinition of functions

I'm trying to scan numbers into 2 2D arrays, and I keep on getting the error of redefinition.
The code:
#include <stdio.h>
#define N 3
void getMatrix(double mat[N][N]);
/*
char getMenuOption();
void getCoordinates(int*, int*);
void sumMatrices(double mat1[][N], double mat2[][N]);
void changeMatrix(double mat[][N]);
void printMatrix(double mat[][N]);
*/
int main() {
double A[N][N], B[N][N];
/*
char option;*/
getMatrix( A[N][N]);
getMatrix( B[N][N]);
/*
option = getMenuOption();*/
return 0;
}
void getMatrix(double A[N][N]){
int i;
for(i=0;i<=N;i++){
for(i=0;i<N;i++)
{
scanf("%lf",&A[N][N]);
}
}
return;
}
void getMatrix(double B[N][N]){
int i;
for(i=0;i<=N;i++){
for(i=0;i<N;i++)
{
scanf("%lf",&B[N][N]);
}
}
return;
}
I guess the problem is that the same function is called twice, but im not so sure about it.
If anyone can help me point to the problem, it will be most welcome.
You don't need to define a function twice (to call it twice or more). One function can be called multiple times, that's the reason of having functions in first place. Get rid of
void getMatrix(double B[N][N]){
int i;
for(i=0;i<=N;i++){
for(i=0;i<N;i++)
{
scanf("%lf",&B[N][N]);
}
}
return;
}
Having said that, you should call the function like
getMatrix(A);
getMatrix(B);
To pass the array (the decay to pointer, anyway). The notation A[N][N] denotes a member of the array and for an array defined like
double A[N][N];
it's off-by-one, as array indexing in C starts from 0.
The function is defined twice
First definition
void getMatrix(double A[N][N]){
int i;
for(i=0;i<=N;i++){
for(i=0;i<N;i++)
{
scanf("%lf",&A[N][N]);
}
}
return;
}
Second definition
void getMatrix(double B[N][N]){
int i;
for(i=0;i<=N;i++){
for(i=0;i<N;i++)
{
scanf("%lf",&B[N][N]);
}
}
return;
}
Take into account that these calls of the function are invalid
getMatrix( A[N][N]);
getMatrix( B[N][N]);
The arguments have type double instead of arrays or pointers.
You should remove one definition of the function and declare the function correctly.
If the compiler allows to use Variable Length Arrays then the functiuon should be declared like
void getMatrix(size_t n, double A[n][n]);
if Variable Length Arrays are not supported by the compiler then N must be a constant and the function indeed can be declared like
#define N SOME_VALUE
//...
void getMatrix( double A[N][N] );
and call the function like
in the first case
getMatrix( N, A );
getMatrix( N, B );
and in the second case
getMatrix( A );
getMatrix( B );

Creating matrix issue

I'm having some trouble creating a user-input matrix through a function I create. The function is as follows:
int create(int l, int c, int one[MAX][MAX])
{
for(int i = 0; i < l; ++i)
for(int j = 0; j < c; ++j)
scanf("%d", &one[i][j]);
}
I then proceed to call my function from main :
int main()
{
int mat[MAX][MAX];
int lines, collumns;
printf("Input # of lines, columns:\n");
scanf("%d %d", &lines, &collumns);
create(lines, collumns, mat[MAX][MAX]);
}
Oddly, if I copy the function to main and just run it as so, it works fine. But it just won't work if I try doing so through function calling, as my program crashes. What am I doing wrong guys?
Change
create(lines, collumns, mat[MAX][MAX]);
to
create(lines, collumns, mat);
and try again.
Well, when passing multidimensional arrays into a function in C, the basic rule is
You should specify the value for each of the dimension other than the first one.
So when you are passing a 2D array, define like this.
int create( int l, int c, int one[][MAX] ){...}
And when passing 3D array, define like this.
int create3D( int x, int y, int z, int mat[][MAX_Y][MAX_Z] ){...}
And when invoking the function, you only need to specify the name of the array variable. No need to specify the dimensions.
create( l, c, one );
create3D( x, y, z, mat );
You can see these errors/warnings if you compile with -Wall switch in gcc.
Good Luck!

Resources