0
Good evening, I have a question, which is the following.
-Write a program that dynamically allocates an array (of integers) of dimensions defined by user. Then fill in the matrix positions and print out all the elements. At the end, create a function that receives a value and returns 1 if the value is in the matrix or returns 0 if it is not in the matrix.
I don’t know how to pass a matrix that’s been allocated to a function. I would have to pass the number of rows and columns, into the function I could go through the matrix with a loop ? or would I not need ? Obg
I made the following code: (Note: Contains error, does not return the expected value). Sorry I couldn’t add code to the forum, I tried my 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;
}