I declare hws globally and try to return it in this method but I get a pointer error. I was wondering if anyone knew why that is and could suggest a solution? Randomize just get a random number.
extern int hws[100][20];
int randomize()
{
int value;
int tru_fals = 0;
value = -1;
while ( tru_fals != 1 )
{
value = rand();
if ( 0 < value )
{
if( 101 > value )
{
tru_fals = 1;
}
}
}
return value;
}
int *populate()
{
int i, j;
i = 0;
j = 0;
while( i < 20 )
{
while ( j < 100)
{
int temp = randomize();
hws[i][j] = temp;
j++;
}
i++;
}
return hws;
}
Except when it is the operand of the
sizeof,_Alignof, or unary&operator, or is a string literal being used to initialize another array in a declaration, an expression of type “N-element array ofT” will be converted (“decay”) to an expression of type “pointer toT“, and its value will be the address of the first element in the array (6.3.2.1/3).In the line
return hws;inpopulate, the type of the expressionhwsis “100-element array of 20-element array ofint“; by the rule above, it will be converted to type “pointer to 20-element array ofint“, orint (*)[20]. Thus, the correct declaration forpopulatewould need to bewhich reads as
and the type of whatever you return the result to would need to be
int (*)[20]as well.Having said that…
Using global variables this way is highly discouraged for a number of reasons. It would be better to pass the array in to
populateas a parameter, like so:You would call this as simply
If you’re using a compiler that supports variable length arrays (either a C99 compiler or a C2011 compiler that does not define
__STDC_NO_VLA__or defines it to 0), you could define the function asand call it as
so you’re not hardcoding the 20 anywhere.
If you aren’t using a compiler that supports variable length arrays, and you don’t want to hardcode the number of rows in the function prototype, you can do something like this:
and call it as
In this case, instead of passing a pointer to the array, we pass a pointer to the first element (the address value is the same, but the type is
int *instead ofint (*)[20]. So thepopulatefunction treats it like a 1D array, and computes the offset withi * rows + j. Note that this trick will only work for 2D arrays that have been allocated contiguously.This also means that
populatecan work with arrays of any size, not just Nx20.