Pointers and multidimensional arrays

From LPTMS Wiki
Revision as of 16:06, 13 November 2012 by Roux (talk | contribs) (Created page with " Handling arrays and pointers. The syntax uses the c99 standard. To compile, use :> gcc -std=c99 main.c <source lang='c'> #include <stdio.h> void f(int * p,int L) { for(i...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Handling arrays and pointers. The syntax uses the c99 standard. To compile, use

:> gcc -std=c99 main.c

<source lang='c'>

  1. include <stdio.h>

void f(int * p,int L) {

 for(int i=0;i<L;i++)
   *(p+i) = 3;

}

void g(double * p,int L) {

 for(int i=0;i<L;i++)
   for(int j=0;j<L;j++)
     *(p+i*L+j) = 2.0*i+j;

}

void h(double * p,int L) {

 for(int i=0;i<L;i++)
   for(int j=0;j<L;j++)
     for(int k=0;k<L;k++)

*(p+(i*L+j)*L+k) = i+j+k; }

int main() {

 int L=3;
 // one-dimensional array
 int tab[L];
 f(&tab[0],L);
 for(int i=0; i<L;i++)
   printf("%d ",tab[i]);
 printf("\n");
 printf("\n");
 // two-dimensional array
 double mat[L][L];
 g(&mat[0][0],L);
 for(int i=0; i<L;i++)
   for(int j=0; j<L;j++)
     printf("%d %d %lf\n",i,j,mat[i][j]);
 printf("\n");
 // three-dimensional array
 double tensor[L][L][L];
 h(&tensor[0][0][0],L);
 for(int i=0; i<L;i++)
   for(int j=0; j<L;j++)
     for(int k=0; k<L;k++)

printf("%d %d %d %lf\n",i,j,k,tensor[i][j][k]);

 return 0;

} </source>