Reputation: 185
I am writing a function where it reads in the files and store characters in a 2 dimensional array. I want this to be a global variable as I want multiple functions outside of the main method to be able to access it, but the dimensions cannot be set until after I've read the file, so what would the be approach in doing this. I've read a fair few posts in stack overflow before asking this question, but I'm still confused/ the questions don't help me with this specific problem.
(I am restricted to using the libraries/functions available with ANSI c)
Upvotes: 1
Views: 127
Reputation: 5217
You would need a pointer type, for example uchar*. Then at runtime, when you know the dimensions m x n, you would need to use malloc, like:
uchar *matrix = (uchar*)malloc(m * n * sizeof(uchar))
And then to navigate it you would use a function that takes into account strides:
int stride = m;
// for element (i,j)
matrix[i * stride + j];
Upvotes: 0
Reputation: 58244
You want to use malloc
:
int i;
t_data * rows;
t_data ** array;
// Allocate the 2d array as a dynamic 1d array of pointers to rows
array = malloc(sizeof(t_data *) * num_rows);
// Allocate each row as a dynamic 1d array of t_data
for ( i = 0; i < num_rows; i++ )
array[i] = malloc(sizeof(t_data) * num_cols);
Here, t_data
is the data type of the data you want to store (for each array element), num_rows
is the read number of rows, and num_cols
is the read number of columns.
You can access elements via array[i][j]
.
When you're done with the array, you free it "in reverse":
for ( i = 0; i < num_rows; i++ )
free(array[i]);
free(array);
Upvotes: 2
Reputation: 2170
Anything that needs 'dynamic' sizing in C, will require the use of pointers, malloc()
, free()
, and related tools. Do a search online (or in a book, if you have one) for dynamic memory allocation.
Note though that this is a fairly broad topic (with associated learning curves and pitfalls), so if you come back with some code that you've implemented, we can help better with any directly related issues.
Upvotes: 0