How can I access the elements of an integer array using pointer arithmetic?
I am clear that to access those of a vector is such that *(vector+"posicion")
but for a matrix I do not know how I can do it.
I know that they can be written in the normal way, matriz[i][j];
but not with pointers and for more that I have searched I have not found a site where they explain it correctly.
I have been practicing and for this I have made a super basic program that asks the user the number of rows and columns that are going to be required and that I fill the matrix manually and then show it but I would like to implement it with pointer arithmetic.
int main() {
int **matriz;
int i , filas , columnas;
printf("\nIntroduce el numero de filas de la matriz: ");
fflush(stdin);
scanf("%i",&filas);
printf("\nIntroduce el numero de columnas de la matriz: ");
fflush(stdin);
scanf("%i",&columnas);
matriz = (int**)malloc(filas*sizeof(int)); //Reservamos el espacio para las filas
if(matriz == NULL)
{
printf("\nError, no se ha podido reservar el espacio...");
exit(1);
}
for(i = 0; i < filas; i++)
{
matriz[i] = (int*)malloc(columnas*sizeof(int)); //Reservamos espacio para las columnas
if(matriz[i] == NULL)
{
printf("\nError, no se ha podido reservar el espacio...");
exit(1);
}
}
IntroducirDatos(matriz , filas , columnas);
MostrarMatriz(matriz , filas , columnas);
return 0; }
And the functions of Enter Data and Show Matrix:
void IntroducirDatos(int **matriz , int filas , int columnas) {
int i, j;
for (i = 0; i < filas; i++) //Introducimos datos
{
for(j = 0; j < columnas; j++)
{
printf("\nIntroduce el valor para la posicion (%i , %i): ", i+1, j+1);
scanf("%i",&matriz[i][j]);
}
}
}
Show Matrix
void MostrarMatriz(int **matriz , int filas , int columnas) {
int i, j;
printf("\nLa matriz es: \n\n");
for(i = 0; i < filas; i++)
{
for(j = 0; j < columnas; j++)
{
printf("|%i ", matriz[i][j]);
}
printf("\n");
} }
Any ideas on how to do it?