Passing table to a function

From LPTMS Wiki
Revision as of 22:27, 26 November 2012 by Roux (talk | contribs) (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...")

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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

/* gcc -std=c99 code.c */

#include "stdio.h"
#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;
}