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 */
Related
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;
}
}
}
I have structure to hold pointer to array of input numbers. When I create matrix I also create default data array. As I suppose the m.data = data; means that m.data pointer points at first element of the array. When I print data right after alocation everything seems ok. But when I print them after in the main function the result is different.
Why does output differs(commented sections)?
#include <stdio.h>
#include <stdlib.h>
typedef struct matrix {
int *data;
int rows;
} Matrix;
//Create Matrix
extern Matrix create_matrix(int size)
{
int data[size * size];
int i = 0;
for(i = 0; i < size * size; i++)
{
data[i] = 0;
}
Matrix m;
m.data = data;
for(i = 0; i < size * size; i++)
{
printf("%d\n",*(m.data + i)); //<--- m.data {0,0 ..... ,0,0,0}
}
m.rows = size;
return m;
};
extern void supply_row_data(Matrix m, int row, int* data)
{
int i = 0;
for(i = 0; i < m.rows; i++)
{
m.data[i] = data[i];
}
};
int main(){
int size = 4;
Matrix m = create_matrix(size);
int i = 0;
int *j = m.data;
for(i = 0; i < size * size; i++)
{
//*(j + i) = i;
printf("%d\n", *(j + i));
}
getch();
}
int data[size * size];
This is a local variable (array) to the function create_matrix It goes out of scope when the function terminates.
m.data = data;
This does not copy the data in the variable data to the data in the variable m.data but rather sets the pointer m.data to the beginning of the array data. When the function returns, the Matrix returned contains what is called a dangling pointer: a pointer to data that no longer exists.
Use the advice from #RSahu to fix this.
That's not how you can copy the data from an array in C.
You need to:
Allocate memory for the data.
m.data = malloc(sizeof(int)*size*size);
Copy the data one element at a time or using memcpy.
memcpy(m.data, data, sizeof(int)*size*size);
Make sure you deallocate the memory allocated to hold the matrix data.
free(m.data);
You should avoid using pointer to local data once function return address of array is no loger valid try to allocate array in following way
int* allocate_vector(size_t elem, int value){
int* vec = (int *) calloc(elem, sizeof(int));
int i = 0;
for( ; i < elem; i++){
*(vec + i) = value;
}
return vec;
}
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).
I would like a function to return an array, or a pointer to an array, in either c or c++, that does something like the following:
double[][] copy(double b[][], int mx, int my, int nx, int ny)
{
double[nx][ny] a;
int i,j;
for(i = mx; i<= nx; ++i)
for(j = my; j<= ny; ++j)
a[i][j] = b[i][j];
return a;
}
void main(void){
double A[2][3];
double B[2][3] = {{1,2}{3,4}{5,6}};
A = copy(B,0,0,1,2);
}
This is the proper method for returning an array from a function is as follows:
#define NUM_ROWS (5)
#define NUM_COLS (3)
char **createCharArray(void)
{
char **charArray = malloc(NUM_ROWS * sizeof(*charArray));
for(int row = 0; row < NUM_ROWS; row++)
charArray[row] = malloc(NUM_COLS * sizeof(**charArray));
return charArray;
}
In this example, the above function can be called like this:
char **newCharArray = createCharArray();
newCharArray can now be used:
char ch = 'a';
for(int row = 0; row < NUM_ROWS; row++)
for(int col = 0; col < NUM_COLS; col++)
newCharArray[row][col] = ch++;
An array can be passed as an argument to function similarly:
void freeCharArray(char **charArr)
{
for(int row = 0; row < NUM_ROWS; row++)
free(charArr[row]);
free(charArr);
}
You can return the double ** from your copy function like this.
double ** copy(double *src, int row, int col)
{
// first allocate the array with required size
double **copiedArr = (double **) malloc(sizeof(double *)*row);
for(int i=0;i<row;i++)
{
// create space for the inner array
*(copiedArr+i) = (double *) malloc(sizeof(double)*col);
for(int j=0; j<col; j++)
{
// copy the values from source to destination.
*(*(copiedArr+i)+j) = (*(src+i+j));
}
}
// return the newly allocated array.
return copiedArr;
}
call to this function is done like this.
double src[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
double **dest = copy(&src[0][0],3,3); //here is your new array
Here you have to assign returned value of copy() to double** not to double[][].
If you try to assign the returned value to array then it will generate "Incompatible types" error (detail).
As memory allocated to copiedArray on the heap so you have to take responsibility to clear the memory.
void freemem(double **mem, int row)
{
for(int i=0;i<row; i++)
{
free(*(mem+i));
}
free(mem);
}
I also want to point out some correction in your sample code:
return type of main should be int.
one should put the return statement at the end of main.
you can't return the stack allocated value, it is cause of crash
in most of cases.
Can someone wiser than I please explain to me why the following code segment faults? There is no problem allocating the memory by reference, but as soon as I try to assign anything or free by reference, segfault occurs.
I'm sure I'm missing some fundamental concept about pointers and passing by reference, hopefully some light can be shed.
#include <stdlib.h>
#include <stdio.h>
void allocateMatrix(float ***);
void fillMatrix(float ***);
void freeMatrix(float **);
int main() {
float **matrix;
allocateMatrix(&matrix); // this function calls and returns OK
fillMatrix(&matrix); // this function will segfault
freeMatrix(matrix); // this function will segfault
exit(0);
}
void allocateMatrix(float ***m) {
int i;
m = malloc(2*sizeof(float*));
for (i = 0; i < 2; i++) {
m[i] = malloc(2*sizeof(float));
}
return;
}
void fillMatrix(float ***m) {
int i,j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
(*m)[i][j] = 1.0; // SEGFAULT
}
}
return;
}
void freeMatrix(float **m) {
int i;
for (i = 0; i < 2; i++) {
free(m[i]); // SEGFAULT
}
free(m);
return;
}
One set of problems is here:
void allocateMatrix(float ***m) {
int i;
m = malloc(2*sizeof(float*));
for (i = 0; i < 2; i++) {
m[i] = malloc(2*sizeof(float));
}
return;
}
You need to assign to *m to get the information back to the calling code, and also you will need to allocate to (*m)[i] in the loop.
void allocateMatrix(float ***m)
{
*m = malloc(2*sizeof(float*));
for (int i = 0; i < 2; i++)
(*m)[i] = malloc(2*sizeof(float));
}
There's at least a chance that the other functions are OK. The fillMatrix() is written and invoked correctly, though it could be simplified by losing the third * from the pointer:
void fillMatrix(float **m)
{
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
m[i][j] = 1.0;
}
}
It might be advisable to pass the triple-pointer to freeMatrix() so that you can zero the pointer in the calling function:
void freeMatrix(float ***m)
{
for (int i = 0; i < 2; i++)
free((*m)[i]);
free(*m);
*m = 0;
}
Calling then becomes:
allocateMatrix(&matrix);
fillMatrix(matrix);
freeMatrix(&matrix);
Good use of indirection. Just try to be consistent with format. It improves readability and reduces errors. e.g.
function calls:
allocateMatrix &matrix
fillMatrix &matrix
freeMatrix &matrix
declarations
void allocateMatrix float ***m
void fillMatrix float ***m
void freeMatrix float ***m
handling
(*m)[i] = malloc(2 * sizeof(float))
(*m)[i][j] = 1.0
free (*m)[i]
Returning of pointer from your function is probably the better way to allocate memory:
float **allocateMatrix() {
int i;
float **m;
m = malloc(2*sizeof(float *));
for (i = 0; i < 2; i++) {
m[i] = malloc(2*sizeof(float));
}
return m;
}
int main() {
float **m;
m = allocateMatrix();
/* do other things
fillMatrix(matrix);
freeMatrix(&matrix);
*/
}