I am trying to create a 2d array in C. The following functions are helper functions. However, when I run the program, using d = 5, my output should be a 5x5 matrix, with values descending from 25 to 0. Instead I am getting...
-86 -87 -88 -89 -90
-91 -92 -93 -94 -95
-96 -97 -98 -99 -26
-27 -28 -29 -30 -31
-32 -33 -34 -35 -36
Why?
int* init()
{
int arr[d][d];
int* p;
p = &arr[0][0];
int r;
int c;
int place = 0;
int num = d*d;
for (r=0;r<d*d;r++)
{
for (c=0;c<d;c++)
{
*(p + place) = num;
num--;
place++;
}
}
return p;
}
void draw(int* p)
{
int r;
int c;
int num = 0;
for (r=0;r<d;r++)
{
for (c=0;c<d;c++)
{
printf("%i ",*(p+num));
num++;
}
printf("\n");
}
}
init; your outer-loop should break on the conditionr<d, notr<d*d. 2.arrceases to exist as soon asinitreturns, giving your omitted caller a non-derefererencable pointer, and efforts to dereference will invoke undefined behavior. 3. An MCVE should be provided, which this is not.