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;
}