0

I have some C code that works as:

int main(void)
{
   printf("Height: ");
   int height;
   do
   {
     height = get_int();
   } while (height < 0 || height > 23);

   char mtn[height][2*height+2];

   for(int i = 0;i <height+1;i++){
       for (int j = 0;j<2+height+3;j++){            
          mtn[i][j] = ' ';            
       }
   }    
}

but would like to make the double for loops a function, something like:

char space_mtn(int height);
int main(void)
{
  printf("Height: ");
  int height;
  do
  {
    height = get_int();
  } while (height < 0 || height > 23);

  char mtn[height][2*height+2];
  strcpy(mtn,space_mtn(height);

}

char space_mtn(int height){
char mtn[height][2*height+2];
for(int i = 0;i <height+1;i++){
    for (int j = 0;j<2+height+3;j++){            
        mtn[i][j] = ' ';            
    }
}

}

but it's not working.

DCR
  • 14,737
  • 12
  • 52
  • 115

1 Answers1

1

Arrays cannot be returned by value in C. One way is to pass the array as a parameter. (Array parameters are adjusted to pointers so that it appears as if the array has been passed by reference, so the function can modify the original array).

void space_mtn(int height, char mtn[height][2*height+2])
{
    for(int i = 0;i < height;i++)
        for (int j = 0; j < 2*height+2 ;j++){           
            mtn[i][j] = ' ';            
}

int main(void)
{
    // ...
    char mtn[height][2*height+2];
    space_mtn(height, mtn);
}

Note, I adjusted the loop bounds on your filler loop - they were nonsense and/or writing out of bounds.

Also, passing arrays of runtime bound to functions does not have compile-time bounds checking available of course -- so you need to take extra care that the bound in the parameter matches the array you are passing.

M.M
  • 138,810
  • 21
  • 208
  • 365