How to pass an array that was allocated to a function in C?

0

Good evening, I have a question, which is as follows.

-Enter a program that dynamically allocates an array (of integers) of dimensions defined by the user. Then fill in the positions of the matrix and print out all the elements. In the end, create a function that receives a value and returns 1 if the value is in the array or returns 0 if it is not in the matrix.

I do not know how to pass an array that has been allocated to a function. I would have to pass the amount of rows and columns, into the function I can traverse the array with a loop? or would it not be necessary? Obg

I made the following code: (Note: Contains error, does not return expected value). Sorry for not adding code in the forum, tried the best.

#include <stdio.h>

int contem(int **matriz, int linha, int coluna, int num){
	int j, i, r;
	for(i = 0; i<linha; i++){
		for(j = 0; j<coluna; j++){
			if(matriz[i][j] == num){
				r = 1;
			}else{
				r = 0;
			}
		}
	}
	
	return r;
}

int main(){

	int num;
	int **matriz, i, j;
	int linhas, colunas;
	
	printf("Informe a quantidade de linhas da matriz: \n");
	scanf("%d", &linhas);
	printf("Informa a quantidade de colunas da matriz: \n");
	scanf("%d", &colunas);
	
	matriz = (int **)malloc(linhas * sizeof(int*));
	for(i = 0; i< linhas; i++){
		matriz[i] = (int *)malloc(colunas * sizeof(int));
	}
	
	for(i = 0; i<linhas; i++){
		for(j=0; j<colunas; j++){
			scanf("%d", &matriz[i][j]);
		}
	}
	
	printf("\n\nDADOS:\n");
	for(i = 0; i<linhas; i++){
		for(j=0; j<colunas; j++){
			printf("%d ", matriz[i][j]);
		}
		printf("\n");
	}
	
	printf("Infofme um numero: \n");
	scanf("%d", &num);
	
	printf("%d ", contem(matriz, linhas, colunas, num));
	
	//liberação de memoria.
	for(i = 0; i<linhas; i++){
		free(matriz[i]);
	}
	
	free(matriz);

	return 0;
}
    
asked by anonymous 16.11.2017 / 03:02

1 answer

0

Good afternoon, I used an array with already defined rows and columns, I hope I have correctly interpreted the doubt and that the code is understandable.

int valor_matriz(int mat[][5]);

int main(){

#define LIN 5
#define COL 5

int mat[LIN][COL];
int i,j,r;

for(i=0;i<LIN;i++){  //Preenchendo Matriz
    for(j=0;j<COL;j++){
        scanf("%d", &mat[i][j]);
    }
   printf("\n");
}

for(i=0;i<LIN;i++){  //Printando Matriz
    for(j=0;j<COL;j++){
        printf("%8d", mat[i][j]);
    }
    printf("\n");
}

r= valor_matriz(mat); //Chamado da Função

printf("%d", r);

return 0;

}

int valor_matriz(int mat[][5]){

int x,y;
int n,r;

printf("Digite um valor para verificar na matriz:");
scanf("%d", &n);

for(x=0;x<5;x++){  //Percorre a Matriz em Busca do Valor Digitado
    for(y=0;y<5;y++){
        if(mat[x][y]==n){
            r=1;
            break;  //Ao encontrar,encerra o ciclo pois ja encontrou ao menos um valor igual ao digitado
        }else{
            r=0;  //Nao encontrou o valor na matriz
        }
    }
}


return r;

}
    
19.11.2017 / 17:51