[英]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. 我正在尝试编写一个代码,它将在main中定义一个数组,在fillArray中使用随机浮点填充该数组,然后在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.
如果我将整个代码打包在main中,它就能完美运行。 I am just having issues with the segmentation fault.
我只是遇到了分段错误的问题。
Thanks in advance for the help! 先谢谢您的帮助!
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++) 你可能意味着(列= 0;列<5;列++)
There are many issues with this code, but you can find them after you fix the most important, which is the loop condition above. 这段代码有很多问题,但你可以在修复最重要的代码后找到它们,这就是上面的循环条件。
I guess you just used the wrong variable row
instead of column
in your second loop 我猜你刚在第二个循环中使用了错误的变量
row
而不是column
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.