2D arrays

I need to use arrays to solve this problem, i have to pass an array to a function but i dont know what length it will have, although i know it will have 4 columns but undefined rows. This array will be created by reading a file so its rows depend on the length of the file. Is there a way of knowing the length at compile time or passing the array to the function with the undefined row length. pls use begginer code. we didnt even learn vectors yet.
Thank you!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>

// First argument is an array of unspecified length. Each element in the
// array is another array of length 4.  When multi-dimensional arrays,
// only the first index can have an unspecified length.
//
// The actual size is passed in the "size" argument.
void processArray(int numbers[][4], unsigned size)
{

    for (unsigned i = 0; i < size; ++i) {
	std::cout << numbers[i][0] << ' '
		  << numbers[i][1] << ' '
		  << numbers[i][2] << ' '
		  << numbers[i][3] << ' '
		  << '\n';
    }
}

int
main()
{
    int numbers[100][4];
    unsigned size {0};

    // while you successfully read 4 numbers from cin, add 1 to size
    while (std::cin >> numbers[size][0]
	   >> numbers[size][1]
	   >> numbers[size][2]
	   >> numbers[size][3]) {

	++size;
    }
    
    processArray(numbers, size);
    return 0;
}

Input:
1 2 3 4
5 4 3 2
9 8 7 6
33 44 55 66

Output is the same.
Have you noticed that you have to know more, understand more, do much more low-level coding, and be more careful when using the "begginner code" than when using something like std::vector?

Passing to a function, see 'Arrays as parameters' in http://www.cplusplus.com/doc/tutorial/arrays/


Reading from a file you have two strategies:

1. Allocate statically, during compilation, "enough" space. During runtime use as much as needed. If the enough is not enough, then you do have a problem.

2. Allocate memory dynamically, during runtime, for the data that you do know is there. There might be a need to reallocate and copy if there is more data than anticipated. You need to remember to manage the allocated memory, i.e. deallocate properly at the end.
Topic archived. No new replies allowed.