lunes, 16 de diciembre de 2013

Pruebas manejo de punteros y matrices en C

Compilador: gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5)
Compilation flags -Wall -g

Código 1:
// matrix operations
#include <stdio.h>

void myPrint(int **table, int x, int y);

int main(int argc, char **argv) {

  int matrix[3][3];

  matrix[0][0] = 2;
  matrix[0][1] = 3;
  matrix[0][2] = 5;

  matrix[1][0] = 1;
  matrix[1][1] = 4;
  matrix[1][2] = 16;

  matrix[2][0] = 9;
  matrix[2][1] = 28;
  matrix[2][2] = 14;

  myPrint(matrix, 2, 1);
  return 0;
}

void myPrint(int **table, int x, int y) {

  printf("%d\n", table[x][y]);
}


Compilación:
warning: passing argument 1 of ‘myPrint’ from incompatible pointer type
note: expected ‘int **’ but argument is of type ‘int (*)[3]’

Ejecución:
Fallo de segmentación

Código 2:
// matrix operations
#include
<stdio.h>

void myPrint(int table[3][3], int x, int y);

int main(int argc, char **argv) {

  int matrix[3][3];

  matrix[0][0] = 2;
  matrix[0][1] = 3;
  matrix[0][2] = 5;

  matrix[1][0] = 1;
  matrix[1][1] = 4;
  matrix[1][2] = 16;

  matrix[2][0] = 9;
  matrix[2][1] = 28;
  matrix[2][2] = 14;

  myPrint(matrix, 2, 1);
  return 0;
}


void myPrint(int table[3][3], int x, int y) {

  printf("%d\n", table[x][y]);
}


Compilación: sin warnings
Ejecución:
28

Código 3:
// matrix operations
#include
<stdio.h>
#include <stdlib.h>

void myPrint(int **table, int x, int y);

int main(int argc, char **argv) {

  int *matrix[3];

  matrix[0] = malloc(3*sizeof(int));
  matrix[0][0] = 2;
  matrix[0][1] = 3;
  matrix[0][2] = 5;

  matrix[1] = malloc(3*sizeof(int));
  matrix[1][0] = 1;
  matrix[1][1] = 4;
  matrix[1][2] = 16;

  matrix[2] = malloc(3*sizeof(int));
  matrix[2][0] = 9;
  matrix[2][1] = 28;
  matrix[2][2] = 14;

  myPrint(&matrix, 2, 1);
  return 0;
}


void myPrint(int **table, int x, int y) {

  printf("%d\n", table[x][y]);
}


Compilación: warning: passing argument 1 of ‘myPrint’ from incompatible pointer type
note: expected ‘int **’ but argument is of type ‘int * (*)[3]’

Ejecución:
28


No hay comentarios: