user2998283
user2998283

Reputation: 51

Segmentation Fault When Calling Function

I'm trying to write a code that will define an array in main, populate that array with random floats in fillArray, and then print the array in printArray. Here is what I have so far.

#include <stdio.h>
#include <stdlib.h>

float fillArray (float array[7][5]);
float printArray (float array[7][5]);

int main ()
{
  float array[7][5];
  fillArray (array);
  printArray (array);
}

float fillArray (float array[7][5])
{
  int row, column;
  for (row = 0; row < 7; row++)
    {
      for (column = 0; row < 5; column++)
        {
          array[row][column] = (float) rand () / (float) RAND_MAX;
        }
    }
}

float printArray (float array[7][5])
{
  int Row, Column;
  for (Row = 0; Row < 7; Row++)
    {
      for (Column = 0; Column < 5; Column++)
        {
          printf ("%4.2f ", array[Row][Column]);
        }
      printf ("\n");
    }
}

which is producing a segmentation fault. I've looked for undefined variables or unallocated memory but couldn't find any, and every other problem posted that I could find dealt specifically with undefined variables (unless I've missed one, and in that case I am extremely sorry). If I package the whole code in main, it works perfectly. I am just having issues with the segmentation fault.

Thanks in advance for the help!

Upvotes: 1

Views: 1209

Answers (2)

zubergu
zubergu

Reputation: 3706

for (row = 0; row < 7; row++)
{
  for (column = 0; row < 5; column++) // column=0,row<5? it is infinite loop and segfault
    {
      array[row][column] = (float) rand () / (float) RAND_MAX;
    }
}

You probably meant for (column = 0; column < 5; column++)

There are many issues with this code, but you can find them after you fix the most important, which is the loop condition above.

Upvotes: 2

SpecialTrooper
SpecialTrooper

Reputation: 104

I guess you just used the wrong variable row instead of column in your second loop

float fillArray (float array[7][5])
{
  int row, column;
  for (row = 0; row < 7; row++)
    {
      for (column = 0; row < 5; column++)
        {
          array[row][column] = (float) rand () / (float) RAND_MAX;
        }
    }
}

which should cause a segmentation fault right here

 array[row][column] = (float) rand () / (float) RAND_MAX;

Upvotes: 1

Related Questions