0

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");
    }
}
3
  • 3
    1. your indexing is wrong in init; your outer-loop should break on the condition r<d, not r<d*d. 2. arr ceases to exist as soon as init returns, 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. Commented Jun 30, 2016 at 0:29
  • 1
    See this answer for #2. Commented Jun 30, 2016 at 0:39
  • Much thanks, WhozCraig and Majora320. Fixed my outer loop and dynamically allocated array. Works fine now! Commented Jun 30, 2016 at 0:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.