fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. enum{DIM=3};
  5.  
  6. int zugriff1(int(*a)[DIM],int x,int y)
  7. {
  8. /* bei zur Compilezeit bekannter Spaltendimension kann der Typ diese Info liefern */
  9. return a[x][y];
  10. }
  11.  
  12. int zugriff2(void*i,int dim,int x,int y)
  13. {
  14. /* bei erst zur Laufzeit bekannter Spaltendimension Nutzung von Zeiger auf VLA + compound literal */
  15. return (int(*)[dim]){i}[x][y];
  16. }
  17.  
  18. int main() {
  19. /* Spaltendimension DIM ist (Compilezeit)konstant */
  20. int a[DIM][DIM];
  21. for(int j=0;j<DIM;++j)for(int k=0;k<DIM;++k) a[j][k]=j*k;
  22.  
  23. for(int j=0;j<DIM;++j,puts(""))for(int k=0;k<DIM;++k)
  24. printf("%d ",zugriff1(a,j,k)); /* hier keine Spaltendimension nötig, da im Typ vorhanden */
  25.  
  26. /* Spaltendimension ist jetzt dynamisch */
  27. int d = DIM;
  28. int *i=malloc(d*d*sizeof*i);
  29. for(int j=0;j<d;++j)for(int k=0;k<d;++k) i[j*d+k]=j*k;
  30.  
  31. for(int j=0;j<d;++j,puts(""))for(int k=0;k<d;++k)
  32. printf("%d ",zugriff2(i,d,j,k));
  33.  
  34. free(i);
  35. return 0;
  36. }
  37.  
Success #stdin #stdout 0s 2244KB
stdin
Standard input is empty
stdout
0 0 0 
0 1 2 
0 2 4 
0 0 0 
0 1 2 
0 2 4