I've got a problem.
I need to write a function which will allocate any 2D array with malloc() but I'm lost and have no idea what might be wrong.
Here is what I wrote so far:
void matrix_ini(int **arr, int SIZE_X, int SIZE_Y);
int main() {
int **arr;
matrix_ini(arr, 2, 3);
return 0;
}
void matrix_ini(int **arr, int SIZE_X, int SIZE_Y) {
srand(time(NULL));
arr = malloc(SIZE_X * sizeof *arr);
for (int i = 0; i < SIZE_X; i++) {
arr[i] = malloc(SIZE_Y * sizeof arr);
}
//initializing array with some numbers:
for (int i = 0; i < SIZE_X; i++) {
for (int j = 0; j < SIZE_Y; j++) {
arr[i][j] = rand()%10;
}
}
}
What exactly am I doing wrong?
Please be gentle, I just started learning. Any tips are welcome.
Problem #1:
This:
arr = malloc(SIZE_X * sizeof(*arr));
Is equivalent to this:
arr = malloc(SIZE_X * sizeof(int*));
Which is OK for your purpose.
But this:
arr[i] = malloc(SIZE_Y * sizeof(arr));
Is equivalent to this:
arr[i] = malloc(SIZE_Y * sizeof(int**));
Which is not OK for your purpose.
So change it to this:
arr[i] = malloc(SIZE_Y * sizeof(int));
Problem #2:
If you want a function to change the value of a variable that you call it with, then you have to call it with the address of that variable. Otherwise, it can change the value of that variable only locally (i.e., within the scope of the function). This pretty much forces you to change the entire prototype, implementation and usage of function matrix_init:
void matrix_init(int*** arr, int SIZE_X, int SIZE_Y)
{
int** temp_arr;
temp_arr = malloc(SIZE_X * sizeof(int*));
for (int i = 0; i < SIZE_X; i++)
{
temp_arr[i] = malloc(SIZE_Y * sizeof(int));
for (int j = 0; j < SIZE_Y; j++)
{
temp_arr[i][j] = rand()%10;
}
}
*arr = temp_arr;
}
Then, in function main, you should call matrix_init(&arr,2,3).
Problem #3:
You should make sure that you release any piece of memory which is dynamically allocated during runtime, at some later point in the execution of your program. For example:
void matrix_free(int** arr, int SIZE_X)
{
for (int i = 0; i < SIZE_X; i++)
{
free(arr[i]);
}
free(arr);
}
Then, in function main, you should call matrix_free(arr,2).
Related
I am trying to initialize an arary using a function but I feel like theres something not right about it. When I compile it I am getting Segmentation Fault but not sure where about. Can someone point me in the right direction where I got wrong. I mean if theres a better way to do it feel free to comment.
Thank you.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void initialize(int ** arr, int row, int col)
{
int i;
arr = (int **) malloc(sizeof(int *) *col);
for(i = 0; i < row; i++)
{
arr[i] = (int *) malloc(sizeof(int) * row);
}
}
void freeArray(int ** arr)
{
free(arr);
}
int main()
{
int **arr;
int r, c;
initialize(arr, 3,6);
for(r = 0; r <= 3; r++)
{
for(c = 0; c <= 6; c++)
{
printf("%d ", arr[r][c] = r*c);
}
printf("\n");
}
freeArray(arr);
}
For starters the function has a bug.
void initialize(int ** arr, int row, int col)
{
int i;
arr = (int **) malloc(sizeof(int *) *col);
for(i = 0; i < row; i++)
{
arr[i] = (int *) malloc(sizeof(int) * row);
}
}
Instead of using the variable col in this statement
arr = (int **) malloc(sizeof(int *) *col);
you have to use the variable row
arr = (int **) malloc(sizeof(int *) *row);
And in this statement instead of using the variable row
arr[i] = (int *) malloc(sizeof(int) * row);
you have to use the variable col
arr[i] = (int *) malloc(sizeof(int) * col);
As for the main problem then the function accepts the pointer declared in main by value. It means that the function deals with a copy of the pointer. Changes of the copy do not reflect on the original pointer.
Either you need to pass the pointer to the function indirectly through a pointer to it (passing by reference) like
void initialize(int *** arr, int row, int col)
{
int i;
*arr = (int **) malloc(sizeof(int *) *row);
for(i = 0; i < row; i++)
{
( *arr )[i] = (int *) malloc(sizeof(int) * col);
}
}
and the function is called like
initialize( &arr, 3,6);
Or it is better when the function allocates arrays and returns a pointer to the arrays like
int ** initialize( int row, int col)
{
int **arr;
arr = (int **) malloc(sizeof(int *) *row);
for( int i = 0; i < row; i++)
{
arr[i] = (int *) malloc(sizeof(int) * col);
}
return arr;
}
and the function is called like
int **arr = initialize( 3, 6 );
Also in the nested for loops in main there are used invalid conditions
for(r = 0; r <= 3; r++)
{
for(c = 0; c <= 6; c++)
{
printf("%d ", arr[r][c] = r*c);
}
printf("\n");
}
You have to write
for(r = 0; r < 3; r++)
{
for(c = 0; c < 6; c++)
{
printf("%d ", arr[r][c] = r*c);
}
printf("\n");
}
Also the function freeArray must be declared and defined the following way
void freeArray(int ** arr, int row)
{
if ( arr != NULL )
{
for ( int i = 0; i < row; i++ )
{
free( arr[i] );
}
}
free( arr );
}
and called like
freeArray(arr, 3);
Pay attention to that in general you need to check whether memory was successfully allocated before using pointers that point to dynamically allocated memory.
I created this function to allocate dynamically a 3D array.
int ***create_3D_Array(int nb_block, int nb_lin, int nb_col) {
int i, j;
int ***A = (int***)malloc(nb_block * sizeof(int**));
for (i = 0; i <nb_col; i++) {
A[i] = (int**)malloc(nb_col * sizeof(int*));
for (j = 0; j < nb_lin; j++) {
A[i][j] = (int*)malloc(nb_lin * sizeof(int));
}
}
return A;
}
I then used it here
int ***all_blocks = NULL;
all_blocks = create_3D_Array(54, 5, 5);
However, it is not working correctly because when I want to give a value to my 6th block all_blocks[5], the program stops working.
Is there any error in my function ?
The dimensions are incorrect in your allocation loops. The outer loop should run to nb_block, the second malloc should allocate nb_lin * sizeof(int*) and the third malloc should allocate nb_col * sizeof(int).
Here is a corrected version:
int ***create_3D_Array(int nb_block, int nb_lin, int nb_col) {
int i, j;
int ***A = (int***)malloc(nb_block * sizeof(int**));
for (i = 0; i < nb_block; i++) {
A[i] = (int**)malloc(nb_lin * sizeof(int*));
for (j = 0; j < nb_lin; j++) {
A[i][j] = (int*)malloc(nb_col * sizeof(int));
}
}
return A;
}
Note that it might be simpler to use a direct 3D array:
int (*all_blocks)[5][5] = malloc(54 * sizeof(*all_blocks));
I'm writing counting sort in C. N is the number of elements in table which is to be sorted, k is max value that any of this element can be. However, this code, leaves me with the same table as the input. What's wrong?
void countingSort(int *tab, int n, int k) {
int *counters = (int *)malloc(k * sizeof(int));
int *result = (int *)malloc(n * sizeof(int*));
for (int i = 0; i < k; i++) {
counters[i] = 0;
}
for (int i = 0; i < n; i++) {
counters[tab[i]]++;
}
int j = 0;
for (int i = 0; i < k; i++) {
int tmp = counters[i];
while (tmp--) {
result[j] = i;
j++;
}
}
tab = result;
}
There are some problems in your code:
int *result = (int *)malloc(n * sizeof(int*)); uses an incorrect size. The array element type is int, not int*. You should write:
int *result = (int *)malloc(n * sizeof(int));
or better:
int *result = (int *)malloc(n * sizeof(*result));
note also that the cast is useless in C, unlike C++ where it is mandatory:
int *result = malloc(n * sizeof(*result));
you could avoid the extra initializing loop by using calloc():
int *counters = calloc(n, sizeof(*counters));
a major problem: the result array is never returned to the caller: tab = result; just modifies the argument value, not the caller's variable. You should instead use the tab array to store the results directly.
you do not free the arrays, causing memory leaks.
you do not test for allocation success, causing undefined behavior if memory is not available. You should return an error status indicating this potential problem.
Here is a corrected version:
// assuming all entries in tab are > 0 and < k
int countingSort(int *tab, int n, int k) {
int *counters = calloc(k, sizeof(*counters));
if (counters == NULL)
return -1;
for (int i = 0; i < n; i++) {
counters[tab[i]]++;
}
int j = 0;
for (int i = 0; i < k; i++) {
int tmp = counters[i];
while (tmp--) {
tab[j++] = i;
}
}
free(counters);
return 0;
}
You pass tab to the function by pointer. However you need to change not the value, but address of the variable. So you should pass address of the pointer to countingSort.
void countingSort(int **tab, int n, int k)
I have a c program in which I want to initialize a 2 dimensional array.
So I made this function :
void initLayer(int **layer, int *dimensions) {
printf("initLayer\n");
layer = malloc(sizeof(int*) * dimensions[0]);
for (int i = 0; i < dimensions[0]; i++) {
layer[i] = malloc(sizeof(int) * dimensions[1]);
}
}
When I use this function there is no problem, but when I try to read the 2D array later I always get a segmentation fault.
I think it may be because the initialization made in the function are not saved when its finished.
Do you know how I could correct my function ? Thank you in advance.
To passing pointer to function you need one more pointer.
int **matrix; is an array of arrays, so to fill it you need to pass it as a pointer, which is int ***layer. but it is weird.
also for changing data by pointer you need to add a star * before it. *layer = ...
#include <stdlib.h>
void initLayer(int ***layer, int *dimensions)
{
*layer = malloc(sizeof(int *) * dimensions[0]);
for (int i = 0; i < dimensions[0]; i++)
{
*(*layer + i) = malloc(sizeof(int) * dimensions[1]);
}
}
int main()
{
int **matrix;
int dimensions[2] = { 4, 6 };
initLayer(&matrix, dimensions);
// then do whatever you want
for (int i = 0; i < dimensions[0]; i++)
{
for (int j = 0; j < dimensions[1]; j++)
{
matrix[i][j] = i * j;
}
}
}
as for me, better to use typedef to make code more readable:
#include <stdlib.h>
typedef int * Array;
typedef int ** Matrix;
void initLayer(Matrix *layer, Array dimensions)
{
*layer = malloc(sizeof(Array) * dimensions[0]);
for (int i = 0; i < dimensions[0]; i++)
{
(*layer)[i] = malloc(sizeof(int) * dimensions[1]);
}
}
int main()
{
Matrix matrix;
int dimensions[2] = { 4, 6 };
initLayer(&matrix, dimensions);
// then do whatever you want
for (int i = 0; i < dimensions[0]; i++)
{
for (int j = 0; j < dimensions[1]; j++)
{
matrix[i][j] = i * j;
}
}
}
When you call the function, the int **layer pointer is copied. So, when you do layer = malloc(...) what actually happens is the function sets its local copy to the malloc result. What you want is to mutate the variable which you called the function with. You can do this by taking a int ***layer and passing in &layer when calling initLayer. Note that you must then use *layer instead of layer in your code.
You have two approaches here:
to pass a reference to the double pointer (***int in this case)
or to return the allocated pointer as the result of your function:
in the first case:
void initLayer(int ***layer, int *dimensions) {
printf("initLayer\n");
*layer = malloc(sizeof(int*) * dimensions[0]);
for (int i = 0; i < dimensions[0]; i++) {
layer[i] = malloc(sizeof(int) * dimensions[1]);
}
}
you pass a reference to a pointer, instead of passing the (uninitialized) pointer. Remember, in C, all parameters are passed by value. In this case, you can call your function as:
...
int**vector;
...
initLayer(&vector, dims); /* you pass the address of your double pointer */
In the second case:
int** initLayer(int *dimensions) {
printf("initLayer\n");
int **layer = malloc(sizeof(int*) * dimensions[0]);
for (int i = 0; i < dimensions[0]; i++) {
layer[i] = malloc(sizeof(int) * dimensions[1]);
}
return layer;
}
in this case, you call it as:
...
int**vector;
...
vector = initLayer(dims); /* you receive your double pointer as a return value */
I've written a piece of code but I'm not sure about how it works.
I want to create an array of pointers and pass it as argument to a function, like the following:
int main()
{
int *array[10] = {0};
for(int i = 0; i < 3; i++)
{
array[i] = (int *)malloc(3*sizeof(int *));
}
testFunction(array);
for(int i = 0; i < 3; i++)
{
free(array[i]);
}
return 0;
}
void testFunction(int *array[3])
{
//do something
return;
}
What I don't understand is the following. I declare array as an array of pointers, allocate memory to it by using malloc and then proceed to call testFunction. I want to pass the array by reference, and I understand that when I call the function by using testFunction(array), the array decays to a pointer to its first element (which will be a pointer also). But why in the parameters list I have to write (int *array[3]) with * and not just (int array[3])?
A parameter of type * can accept an argument of type [], but not anything in type.
If you write void testFunction(int arg[3]) it's fine, but you won't be able to access array[1] and array[2] and so on, only the first 3 elements of where array[0] points to. Also a comversion is required (call with testFunction((int*)array);.
As a good practice, it's necessary to make the function parametera consistent with what's passed as arguments. So int *array[10] can be passed to f(int **arg) or f(int *arg[]), but neither f(int *arg) nor f(int arg[]).
void testFunction(int **array, int int_arr_size, int size_of_array_of_pointers)
{
for(int j = 0; j < size_of_array_of_pointers; j++)
{
int *arrptr = array[j]; // this pointer only to understand the idea.
for(int i = 0; i < int_arr_size; i++)
{
arrptr[i] = i + 1;
}
}
}
and
int main()
{
int *array[10];
for(int i = 0; i < sizeof(array) / sizeof(int *); i++)
{
array[i] = malloc(3*sizeof(int));
}
testFunction(array, 3, sizeof(array) / sizeof(int *));
for(int i = 0; i < sizeof(array) / sizeof(int *); i++)
{
free(array[i]);
}
return 0;
}
Evering depends on what // do something means in your case.
Let's start from simple : perhaps, you need just array of integers
If your function change only values in array but does not change size, you can pass it as int *array or int array[3].
int *array[3] allows to work only with arrays of size 3, but if you can works with any arrays of int option int *array require additional argument int size:
void testFunction(int *array, int arr_size)
{
int i;
for(i = 0; i < arr_size; i++)
{
array[i] = i + 1;
}
return;
}
Next : if array of pointers are needed
Argument should be int *array[3] or better int **array (pointer to pointer).
Looking at the initialization loop (I changed sizeof(int *) to sizeof(int))
for(int i = 0; i < 3; i++)
{
array[i] = (int *)malloc(3*sizeof(int));
}
I suppose you need 2-dimension array, so you can pass int **array but with sizes of two dimensions or one size for case of square matrix (height equal to width):
void testFunction(int **array, int wSize, int hSize)
{
int row, col;
for(row = 0; row < hSize; row++)
{
for(col = 0; col < wSize; col++)
{
array[row][col] = row * col;
}
}
}
And finally : memory allocation for 2D-array
Consider the following variant of your main:
int main()
{
int **array;
// allocate memory for 3 pointers int*
array = (int *)malloc(3*sizeof(int *));
if(array == NULL)
return 1; // stop the program
// then init these 3 pointers with addreses for 3 int
for(int i = 0; i < 3; i++)
{
array[i] = (int *)malloc(3*sizeof(int));
if(array[i] == NULL) return 1;
}
testFunction(array, 3, 3);
// First, free memory allocated for int
for(int i = 0; i < 3; i++)
{
free(array[i]);
}
// then free memory allocated for pointers
free(array);
return 0;
}
Pay attention, that value returned by malloc should be checked before usage (NULL means memory was not allocated).
For the same reasons check can be added inside function:
void testFunction(int **array, int wSize, int hSize)
{
int row, col;
if(array == NULL) // check here
return;
for(row = 0; row < hSize; row++)
{
if(array[row] == NULL) // and here
return;
for(col = 0; col < wSize; col++)
{
array[row][col] = row * col;
}
}
}