Passing table to a function: Difference between revisions

From LPTMS Wiki
Jump to navigation Jump to search
(Created page with "Passing a table to a function either via table type argument or by pointer. <source lang="c"> →‎gcc -std=c99 code.c: #include "stdio.h" #include "stdlib.h" void function...")
 
(No difference)

Latest revision as of 22:27, 26 November 2012

Passing a table to a function either via table type argument or by pointer.

<source lang="c"> /* gcc -std=c99 code.c */

  1. include "stdio.h"
  2. include "stdlib.h"

void function(int n, int tab[]) {

 for(int i=0;i<n;i++) tab[i] = i*i;

}

void function_ptr(int n, int * p) {

 for(int i=0;i<n;i++) *(p+i) = 2*i-1;

}

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

 if(argc != 2)
   {
     printf("\tUsage:\t");
     printf("%s",argv[0]);
     printf(" <integer>\n");
   }
 else
   {
     int n = atoi(argv[1]);
     int t[n];
     printf("Passing table\n");
     function(n,t);
     for(int i=0;i<n;i++) printf("%d ",t[i]);
     printf("\nPassing pointer\n");
     function_ptr(n,&t[0]);
     for(int i=0;i<n;i++) printf("%d ",t[i]);
     printf("\n");
   }
 return 0;

} </source>