C Language, dynamic 3d array - arrays

I have to create a dynamic and 3 dimensional integer-Array in C.
But I have to create the pointers separately and use malloc. I know how to create 2d Array with malloc but I get confused using the following method, and i couldn't really find other question similar to this.
2x2x2 Integer-Array
First step:
int *firstD;
firstD = (int) malloc(2*sizeof(int));
Second step:
int *secondD;
secondD = (int) malloc(2 * firstD * sizeof(int));
Third step:
int *thirdD;
thirdD = (int) malloc(2 * secondD * sizeof(int));
I think maybe I have to add pointers in the starting (int*) and increase it every stepp by one more pointer?

Allocate an array to store pointers to arrays of row pointers.
Allocate arrays to store row pointers.
Allocate arrays to store each rows.
#include <stdlib.h>
int main(void) {
int size1 = 2, size2 = 2, size3 = 2;
int*** array;
array = malloc(sizeof(int**) * size1); // 1
for (int i = 0; i < size1; i++) {
array[i] = malloc(sizeof(int*) * size2); // 2
for (int j = 0; j < size2; j++) {
array[i][j] = malloc(sizeof(int) * size3); // 3
}
}
// free arrays
for (int i = 0; i < size1; i++) {
for (int j = 0; j < size2; j++) {
free(array[i][j]);
}
free(array[i]);
}
free(array);
return 0;
}
I wrote type names explicitly in the above example, but I suggest using dereferencing to obtain size of elements to allocate is better to prevent causing typos.
#include <stdlib.h>
int main(void) {
int size1 = 2, size2 = 2, size3 = 2;
int*** array;
// allocate arrays
array = malloc(sizeof(*array) * size1); // 1
for (int i = 0; i < size1; i++) {
array[i] = malloc(sizeof(*array[i]) * size2); // 2
for (int j = 0; j < size2; j++) {
array[i][j] = malloc(sizeof(*array[i][j]) * size3); // 3
}
}
// free arrays
for (int i = 0; i < size1; i++) {
for (int j = 0; j < size2; j++) {
free(array[i][j]);
}
free(array[i]);
}
free(array);
return 0;
}
Onitted in the above examples to make them simple, but you should check results of malloc() to see if the allocations are successful.

Related

Dynamic memory allocation for two-dimensional arrays

I want to allocate memory for a two-dimensional array (matrix) and write the sums of the diagonals in a separate one-dimensional array. So my code has an array of pointers to pointers,
int N, ** matrix = NULL;
matrix = (int**) malloc(sizeof(int*) * N);
I fill it and then I create an array to store the sums of the diagonals,
int diag = 2 * N - 1;
int *diagonals = NULL;
diagonals = (int*)malloc(sizeof(int) * diag);
but when I want to write a value into an array, something goes wrong, the values just don't get written into the array; I don't know why.
Here is my code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
srand(time(NULL));
int N, ** matrix = NULL;
printf("Input the number of rows\n");
scanf_s("%d", &N);
printf("\n");
// Memory allocation for the array of pointers to pointers
matrix = (int**) malloc(sizeof(int*) * N);
if (matrix != NULL)
{
for (int i = 0; i < N; i++)
*(matrix + i) = (int*)malloc(sizeof(int) * N);
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
matrix[i][j] = rand() % 14 - 4;
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
printf("\n");
int diag = 2 * N - 1;
int *diagonals = NULL;
diagonals = (int*)malloc(sizeof(int) * diag);
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
diagonals[i+j] += matrix[i][j];;
}
}
for (int i = 0; i < diag; i++) {
printf("diagonals[%d] - %d\n",i, *(diagonals+i));
}
}
else
printf("Not enough memory.. oops..\n");
}
The content of diagonals is allocated with malloc() which does not initialize the memory. You should use calloc() which initializes the memory with zeros:
diagonals = calloc(diag, sizeof *diagonals);
The following loop assumes that each element of diagonals was initialized to zero, but you performed no such initialization. As a result, they are uninitialized and will contain whatever value happens to be sitting in the newly-allocated memory.
diagonals = malloc(sizeof(int) * diag);
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
diagonals[i+j] += matrix[i][j];;
}
}
You have several options for zero-initialization:
Use memset to zero the memory, after allocation:
diagonals = malloc(sizeof(int) * diag);
memset(diagonals, 0, sizeof(int) * diag);
Initialize values in a loop:
diagonals = malloc(sizeof(int) * diag);
for (int i = 0; i < diag; i++) diagonals[i] = 0;
Allocate with calloc:
diagonals = calloc(diag, sizeof(int));
Note that in all cases, you should be checking the result of allocation. If it fails and returns NULL, you should not attempt to access memory via that pointer.
It does not answer the question but I would suggest using real 2D arrays instead of arrays of pointers. To dynamically allocate the 2D array you need to use a pointer to array.
int (*matrix)[N] = malloc(N * sizeof(*matrix));
You will have only one allocation and one free. Fever levels of indirection.

How to access a 2d array inside a struct using only pointers

Trying to understand pointers as a beginner in C-
I've got this struct:
typedef struct {
int size; // dimension of array
int **arr; // pointer to heap allocated array
} someStruct;
So I use malloc to generate this struct, and an array, and initialize all the values to zero-
someStruct *m = (someStruct*)malloc(sizeof(someStruct));
m->size = n;
m->arr = (int**)malloc(n * sizeof(int));
// initialize array
for (int i = 0; i < n; i++) {
*(m->arr + i) = (int*)malloc(n * sizeof(int));
// set value to 0
for (int j = 0; j < n; j++) {
*(*(m->arr + i) + j) = 0;
}
}
After this I basically continue to access the array in later stages using the same kind of pointer logic-
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int num = *(*(m->arr + i) + j);
printf("num: %d\n", num);
}
}
Here's the problem- when I try to use this method of access, I'm clearly not getting the right answer- my print output look like this:
num: -2043774080
num: 22031
num: 0
num: 0
...
num: 0
num: 0
Here's the really weird part- this seeming bug of the 'weird' random numbers only comes when I'm creating and accessing an array of size 5-
I've come to believe that the whole
*(*(m->arr + i) + j)
method of access must be wrong- any help on this would be really useful. Thanks in advance, I apologize if this was already answered, my searching was unable to find it.
You should give complete code, but I think I was able to figure out your intent. You have one glaring problem, and many style issues. Here is what I think your code should look like:
typedef struct {
int size; // dimension of array
int **arr; // pointer to heap allocated array
} MagicSquare;
:
:
// no need to dynamically allocate this, it is small
MagicSquare m;
m.size = n;
m.arr = malloc(n * sizeof(int*)); // note it is sizeof(int*), not (int)
// initialize array
for (int i = 0; i < n; i++) {
m.arr[i] = malloc(n * sizeof(int));
// set value to 0
for (int j = 0; j < n; j++) {
m.arr[i][j] = 0;
}
}
:
:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("num: %d\n", m.arr[i][j]);
}
}
Note that if you want to initialize the allocated memory to zero, you should just use calloc, which does this initialization for you:
// initialize array
for (int i = 0; i < n; i++) {
m.arr[i] = calloc(n,sizeof(int));
}

Re loading integers into an array

The code below works fine when M <= 4, but seems to bugger up if you put in a whole number that's any bigger (in this case, I actually need M to be 10). Does anyone know why this is happening and what can be done about it? Thanks.
/*
"Read all 100 numbers from the text file and store it in a 10x10 array."
*/
#include <stdio.h>
#include <stdlib.h>
FILE *fptr;
int n;
int M = 4; // Length and width of array
int main()
{
// Allocating memory
int **myArray = (int **)malloc(M * sizeof(int));
for (int j = 0; j < M; j++) {
myArray[j] = (int *)malloc(M * sizeof(int));
}
// Loading data into array
fptr = fopen("List of Numbers.txt","r");
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
fscanf(fptr,"%d",&n);
// printf("%d ",n);
myArray[i][j] = n;
}
}
fclose(fptr);
// Printing
for (int i = 0; i < M; i++) {
for(int j = 0; j < M; j++) {
printf("%d ",myArray[i][j]);
}
printf("\n");
}
return 0;
}
This line:
int **myArray = (int **)malloc(M * sizeof(int));
should be:
int **myArray = (int **)malloc(M * sizeof(int *));
^
You are allocating an array of pointers, not an array of ints.

Understanding Array of pointers

I am doing something like this;
int main()
{
int *b[2], j;
for (j = 0; j < 2; j++)
{
b[j] = (int *)malloc(12 * sizeof(int));
}
return 0;
}
Please tell me what this instruction really means? And how can I pass this array of pointers to a function to access values like *(B[0]+1),*(B[1]+1) etc?
int main(void)
{
int *b[2], j; // initialization of an array of pointers to integers (size = 2)
for (j = 0; j < 2; j++) // for each of the pointers
{
b[j] = malloc(12 * sizeof (int)); // allocate some space = 12 times size of integer in bytes (usually 4)
}
return 0;
}
If you want to pass this array to a function you can just pass b
foo(b);

Double pointer addresses

I created and allocated a double pointer like this:
int **a;
a = (int**)malloc(10 * sizeof(int *));
for (int i = 0; i < 10; i++)
*(a+i) = (int *)malloc(10 * sizeof(int));
And then I initialized it for example like this:
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
**a = 1;
(*a)++;
}
a++;
}
My problem and question is how can I save the address'es of my double pointer?At this moment I lost them and can't use them anymore.
Don't use explicit pointer arithmetic and dereferencing when array subscripting will do:
int rows = 10, cols = 10
int **a;
// don't cast the return value of malloc
a = malloc(rows * sizeof(*a));
for (int i = 0; i < rows; i++)
a[i] = malloc(cols * sizeof(**a));
...
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
a[i][j] = 1;
}
}
Return a from a function, save it as a class member, it is just like any other variable. If you want to save the contents of the arrays then do that (but that is not what I could call saving a double pointer -- by the way the usual description is "pointer-to-pointer").

Resources