Passing an array as a function paramater

This is a discussion on Passing an array as a function paramater within the C Programming forums, part of the General Programming Boards category; Hi, is the code below OK? Code: #define ROWS 5 #define COLUMNS 6 int some_function(int arr[2][2]) // bounds not equal ...

  1. #1
    kkk
    kkk is offline
    Registered User
    Join Date
    May 2011
    Posts
    32

    Passing an array as a function paramater

    Hi,

    is the code below OK?

    Code:
    #define ROWS 5
    #define COLUMNS 6
    
    int some_function(int arr[2][2]) // bounds not equal to the real bounds of the array being passed
    {
       arr[4][3] = 65; //  Is this OK? Exceeds the bounds specified in the parameter but not the bounds of the "real" array being passed
    }
    
    int main()
    {
       int array[ROWS][COLUMS];
       some_function(array);
    }

  2. #2
    Registered User Inanna's Avatar
    Join Date
    May 2011
    Posts
    69
    It should not compile. The first dimension decays into a pointer, but only the first dimension. You are passing int(*)[6] to a function expecting int(*)[2].

  3. #3
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,531
    > int some_function(int arr[2][2]) // bounds not equal to the real bounds of the array being passed
    Well if you had tried to compile it, you would have found that it wouldn't have compiled anyway.

    At the very least, all the minor dimensions would have to agree with the array you're passing, so
    int some_function(int arr[2][COLUMNS])

    The major dimension is optional to begin with, and ignored by the compiler.
    So you could have also said
    int some_function(int arr[][COLUMNS])
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Passing Array To Function & Display Array Contents
    By mcertini in forum C++ Programming
    Replies: 4
    Last Post: 12-10-2010, 12:32 PM
  2. passing an array to function
    By waysgoose in forum C++ Programming
    Replies: 2
    Last Post: 07-22-2008, 03:59 AM
  3. Passing a paramater by reference
    By g4j31a5 in forum C++ Programming
    Replies: 4
    Last Post: 12-06-2006, 08:48 PM
  4. Replies: 5
    Last Post: 10-28-2006, 11:27 AM
  5. passing array to function
    By chr1zis in forum C++ Programming
    Replies: 2
    Last Post: 02-20-2006, 09:39 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21