Passing table to a function

From LPTMS Wiki
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;
}