0

I have an array of integers: int* list = malloc((m*n) * sizeof(int)); Variables m and n are the required dimensions of a 2d array.

I filled my array with random numbers and printed it with a simple for (int i = 0; i < lines; i++) printf("%d\n", list[i]); Which prints:

4
5
100
7
9
3
74
1
6

My question is how can I print the array as a 2d array instead of 1d?

Here's my attempt:

for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            printf("%d", list[i]);
        }
        printf("\n");
    }

But this prints first n numbers like this:

444
555
100100100

Leaving the rest of the array lost somewhere.

2
  • 3
    list[i] -> list[i*m+j]. Commented Mar 27, 2021 at 13:13
  • @interjay yep that was the solution. Thanks :) Commented Mar 27, 2021 at 14:14

1 Answer 1

1

The first row (i = 0) should print the element 0, 1, ... , m-1.

The second row (i = 1) should print the element m, m+1, ..., 2*m-1.

The ith row should print the element m*i, m*i+1, ... , m*i+m-1.

Therefore, you should print list[i*m+j] instead of list[i].

Also you may want to add some space between the elements in the same row.

Sign up to request clarification or add additional context in comments.

1 Comment

I know about the spaces, I forgot to write that down. This fixed my problem. Thanks a lot :)

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.