Is it possible in anyway to recursively create a given number of arrays in C with predetermined length? I want to experiment with arrays for a clustering project and would be really practical if i could do this.
Yes it is possible, allocate an array of pointers then allocate all the arrays:
T **array = malloc(rows * sizeof *array);
for (i = 0; i < rows; i++)
{
array[i] = malloc(cols * sizeof **array);
}
it create rows numbers of array. Each array is an array of cols numbers of T.
Related
As title, I want to know how to initialize double pointer with sizeof a pointer.
For instance
int **p=malloc(sizeof *p * rows);
for(size_t i = 0; i < rows; i++){
p[i]=malloc(sizeof ? * cols);
}
What should I fill in ?.
Any help would be appreciated.
What should I fill in ?.
In general when you have
X = malloc(sizeof ? * NUMBER);
the ? is to be replaced with the type that X points to. That can simply written as *X.
So the line:
p[i]=malloc(sizeof ? * cols);
is to be:
p[i]=malloc(sizeof *p[i] * cols);
Notice that a 2D array can be created much simpler. All you need is
int (*p)[cols] = malloc(sizeof *p * rows);
Here p is a pointer to an array of cols int. Consequently sizeof *p will be the size of an array of cols int.
Using this VLA based technic means that you can allocate the 2D array using a single malloc. Besides making the code more simple (i.e. only 1 malloc) it also ensures that the whole 2D array is in consecutive memory which may give you better cache performance.
It looks like you want p to be an array that can hold pointers, and the number of pointers is rows. So you can allocate memory for p like this:
int ** p = malloc(sizeof(int *) * rows);
Now if you want p[i] to point to an array that holds cols ints, do this:
p[i] = malloc(sizeof(int) * cols);
I would like to have a dynamic 2D array of chars, max 200 and scan to it.
I am not really sure how to do this, all I came up with is to define the dynamic arrays (and I don't even know if it is right):
char **arr = (char **)malloc( (len+1) * sizeof(char*) );
for (i=0; (len+1)>0; i++)
char *arr1 = (char *) malloc ( (len+1) * sizeof(char) );
But I am not sure what to put in the (len) - let's say I would like an array of 51x150, depending on the scanned input.
How to allocate the array based on the scanned value and print it?
An example of input:
####.#...##
##.##.#.###
##.###.#.##
#.##.##.#..
You probably want to use a real 2D array and not a segmented look-up table.
size_t x = 51; // user input
size_t y = 150; // user input
char (*arr)[y] = malloc( sizeof(char[x][y]) );
...
arr[i][j] = something;
...
free(arr);
This is much faster and safer than a segmented look-up table. This also allows you to memcpy data in and out of the array, even if that data is larger than one line.
This question already has answers here:
A different way to malloc a 2D array?
(3 answers)
Freaky way of allocating two-dimensional array?
(3 answers)
Closed 6 years ago.
Every time I allocate the memory for a 2D array first I create an array of int** and then with a for I allocate the memory for each element.
For example:
int ** arr = malloc(N*sizeof(int *));
for(i=0; i< N; i++) arr[i] = malloc(M*sizeof(int));
Wouldn't be possible allocate the memory like:
int ** arr = malloc(N*sizeof(int[M]));
or
int ** arr = malloc(sizeof(int[N][M]));
in order to avoid the for?
like this : int (*arr)[M] = malloc(sizeof(int[N][M]));
arr is pointer to int[M].
use like arr[0][M-1];
and free(arr);
int ** arr = malloc(N*sizeof(int[M]));
is incorrect C code, if you simulate it by allocating once
int *arr = malloc(N*M*sizeof(int));
and access it by
arr[i*M + j],
this is an analog to arr[I][j] in your first case.
You have a "pointer to pointer". That cannot represent a 2D array.
The correct declaration of a pointer to a 2D array is
// number of elements in one row
#define COLS 10
// number of rows
#define ROWS 20
int (*array)[COLS]; // mind the parenthesis!
That makes array a pointer to array of COLS ints. The type is `int (*)[COLS], btw. but you don't need the type, see below.
To allocate the array you should then use the standard allocation for a 1D array:
array = malloc(sizeof(*array) * ROWS); // COLS is in the `sizeof`
array = malloc(sizeof(int[ROWS][COLS])); // explicit 2D array notation
Which variant to use is personal style. While the first contains no redundancy (consider you change the declaration of array to use INNER instead of COLS or the element-type to float). The second is more clear at a fist glance, but more prone to errors when modifying the declaration of array.
To free:
free(array);
I want to store strings in a 2D array using pointers but I'm confused with how to do it. The examples I've seen use only arrays of ints or use the brackets[] to allocate a fixed size of memory. So I'm trying to initialize my 2D array of strings and this is what I have:
char ** stringArr = (char**)malloc(/*I don't know what goes here*/);
for(i = 0; i < rows; i++)
stringArr[i] = (char*)malloc(cols *sizeof(char));
As you can see the parameter for my first call of malloc, I am stuck as to what to put there if I want an exact x number of rows, where each row stores a string of chars. Any help would be appreciated!
Do this, because you're allocating some number of pointers:
malloc(rows * sizeof(char*))
You will want to use the number of rows.
char ** stringArr = malloc(rows * sizeof(char*));
Also, do not typecast the return value of a malloc() call.
Use sizeof *ptr * N.
Notice how this method uses the correct type even if stringArr was char ** stringArr or int ** stringArr.
stringArr = malloc(sizeof *stringArr * rows);
for(i = 0; i < rows; i++)
stringArr[i] = malloc(sizeof *(stringArr[i]) * cols);
I cannot create a 2D array from 2 variables (eg int arr[i][j] not allowed) so how would I create a dynamically sized 2D array?
The dimensions of the array are only known at runtime in my program. The array is to represent a grid. How would I code this in C?
First allocate an array of pointers.
/* size_x is the width of the array */
int **array = (int**)calloc(size_x, sizeof(int*));
Then allocate each column.
for(int i = 0; i < size_x; i++)
{
/* size_y is the height */
array[i] = (int*)calloc(size_y, sizeof(int));
}
You can access the elements with array[i][j]. Freeing the memory is done in 'reverse' order:
for(int i = 0; i < size_x; i++)
{
free(array[i]);
}
free(array);
You have to allocate a 1-dimensional array:
int* array = calloc(m*n, sizof(int));
And access it like this:
array[i*n + j]
The compiler does exactly this when accessing two-dimensional arrays, and will probably output the same code when n can be guessed at compile time.
This is a FAQ on comp.lang.c (I took the liberty to add the c-faq tag), it even has a FGA (frequently given answer :-)
See http://c-faq.com/aryptr/index.html, 6.16 How can I dynamically allocate a multidimensional array?
In C a multidimensional array is just an array for which each element is another array.
So you need to first allocate memory for one array (the rows). You can use the malloc() function which will return a pointer to the array.
Then you iterate through the array and for each element you allocate memory for the number of columns.
NOTE: don't forget to free the memory you manually allocate with the free() function in the same way you used malloc() to allocate it.
Some of the examples show multiple (more than 2) allocations for the array; it is perfectly feasible to do it in just two allocations (error checking omitted) for an n × m array:
int **array = calloc(m, sizeof(*array));
int *data = calloc(m * n, sizof(*data));
for (int i = 0; i < m; i++)
array[i] = &data[i * n];
...use array[i][j]...
free(array[0]);
free(array);