Thread: declare functions with a variable's size

  1. #1
    Registered User
    Join Date
    Nov 2010

    declare functions with a variable's size

    hello i have this function
    void learn_size(int *size,char *point)
    which finds the *size from a txt file
    then im declaring a function like this
    void read(int xarray[*size][*size])
    as im not able to declare read function with a real number in that xarray array because i do not know it from the beginning and keeps telling me that it does not recognize the *size how can i fix that problem

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Well no, because you could not have declared your array at run-time with a variable size.

    Using a C99 compiler, you can do this.
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    void foo ( int size, int arr[size][size] ) {
      for ( int i = 0 ; i < size ; i++ ) {
    int main ( ) {
      int size = 3;
      int arr[size][size];
      arr[0][0] = 0;
      arr[1][1] = 1;
      arr[2][2] = 2;
      return 0;
    Unless you can guarantee that size will be small, you're better off using malloc to allocate the space. A VLA can blow your stack allocation with zero warning, and no recovery.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Mar 2011
    the other approach is to pass a pointer foo(int size,int *arr) and compute the array indices yourself. for a two dimension array
    you do arr[row * size + col]

    read(int size,int *arr) {
        int i; // row (first) index
        int j; // column (second) index
        // arr[0][0]
        i = 0;
        j = 0;
        arr[i * size + j] = 0;
        // array[0][1]
        i = 0;
        j = 1;
        arr[i * size + j] = 1;
        // array[1][0]
        i = 1;
        j = 0;
        arr[i * size + j] = 2;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 02-07-2010, 01:22 PM
  2. getchar () and declare variable
    By sfff in forum C Programming
    Replies: 7
    Last Post: 10-19-2009, 12:23 AM
  3. Declare a variable in a switch
    By swgh in forum C++ Programming
    Replies: 5
    Last Post: 06-03-2008, 11:55 AM
  4. How To Declare and Dynamically Size a Global 2D Array?
    By groberts1980 in forum C Programming
    Replies: 26
    Last Post: 11-15-2006, 09:07 AM
  5. Declare an operator a variable?
    By bluenoser in forum C Programming
    Replies: 8
    Last Post: 10-19-2002, 09:45 AM