Error in filling static array dynamically in C - c

I have to use a static two-dimensional array and a dynamic matrix as a part of my college task.
So, I've created them, and now trying to fill and then print them to a console, but getting "segmentation fault". That's how I'm trying to achieve it:
#include "arrayutils.h"
#include <stdlib.h>
#include <stdio.h>
#define ROWS 5
#define COLUMNS 7
int main3() {
/*init static array*/
double twodimarray[ROWS][COLUMNS];
/*init dynamic array*/
double **matrix = (double**) malloc(sizeof(double*) * ROWS);
for(int i = 0; i < ROWS; i++) *(matrix + i) = (double*)malloc(sizeof(double) * COLUMNS);
for(int i = 0; i < ROWS; i++){
dfillarran(*(matrix + i), COLUMNS);
dfillarran(twodimarray[i], COLUMNS);
}
puts("Dynamic matrix :");
printmx(matrix, ROWS,COLUMNS);
puts("Static array:");
printmx(twodimarray, ROWS, COLUMNS);
/*freeing mem*/
for(int i = 0; i < ROWS; i++) free(*(matrix + i));
free(matrix);
}
Error is definitely in function printmx(), but I can't understand why; It works for dynamic matrix, and fails only for static one, but static array name - is a pointer to array of pointers, where each one is pointing array of values, just like dynamic one!
There is code of my printmx() function from arrayutils.h:
/**Print Matrix*/
void printmx(double** mx, int rows, int col){
for(int i = 0; i < rows; i++) {
for(int j = 0; j < col; j++){
printf("%.lf ", *(*(mx + i)+j));
}
putchar('\n');
}
putchar('\n');
}
Funcion that fills arrays with random values can be found here, in arrayutils.c, that I've created for all other tasks that use same functions like filling and printing arrays, but I don't think, that problem is there..
Probably, I'm wrong somewhere in theory, and still not getting the difference between static and dynamic matrix, please correct me :)
p.s.There is a screenshot of the error:

The function printmx may not be called for the two objects of different types.
The array twodimarray is a two dimensional array that when is passed to the function has the type double ( * )[COLUMNS].
While matrix is a pointer of the type double **.

Related

Difference between declaring a pointer with and without size

I'm sort of confused between these 2 declarations
int *a;
int (*a)[3]
As I understand it, both of these give us a single pointer pointing to nothing in memory. The 2nd one is shown to be an example of a pointer pointing to an array of 3 ints in memory. But since this memory has not even been allocated, does it make any sense.
To make the pointer point to an array of 3 ints in memory, we need to do a a = (int*)malloc(sizeof(int) * 3). Doing this for the first one AND the second one will both give me a pointer pointing to a memory location where 12 consecutive bytes store my 3 numbers.
So why use int (*a)[3] at all if eventually I have to use malloc ?
So why use int (*a)[3] at all if eventually I have to use malloc ?
It is very useful for variable length arrays when you want to create a real 2d array using dynamic memory:
#include <stdio.h>
#include <stdlib.h>
void *fn_alloc(int rows, int cols)
{
int (*arr)[cols];
int i, j;
arr = malloc(sizeof(int [rows][cols]));
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
arr[i][j] = (i * cols) + j;
}
}
return arr;
}
void fn_print(int rows, int cols, int (*arr)[cols])
{
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("\t%d", arr[i][j]);
}
printf("\n");
}
}
int main(void)
{
int rows, cols;
scanf("%d %d", &rows, &cols);
int (*arr)[cols] = fn_alloc(rows, cols);
fn_print(rows, cols, arr);
free(arr);
return 0;
}
In other words, when dynamic memory is involved, your first declaration is useful for pointing to an array of n dimensions while the second one is useful to point to an array of array of n dimensions.
So why use int (*a)[3] at all if eventually I have to use malloc ?
Because in most such cases (dynamically sized 2D matrixes), you should have some abstract data type using flexible array members. This answer is very relevant to your question (which is a near duplicate).

Using pointers and malloc alone, how to define 2D int array? mine seems doesnt work. (seg fault)

I want to declare 2D-array in .h file without given numbers of COLS nor ROWS (cause they are read somewhere from inside the main() )
I mean I could tried another way of doing this like below
if one of ROWS and COLS is given at the firsthand.
int COLS = 20;
int (*array)[COLS];
array = malloc((*array) * ROWS);
thus I tried like below:
below is 2d.h
int* a;
int** b;
int size;
below is test2d.c, inside int main(){}
read_size() //size value read from some file
a = malloc(sizeof(int) * size);
b = malloc(sizeof(*a) * size);
for(int i=0; i<size; i++){
for(int j=0; j<size; j++){
b[i][j] = i+j;
printf("ok");
}
}
//print all
should be printing all 0112 but the result is segmentation fault.
To allocate a 2D array you need to allocate the 2D pointer b, which you have done. After that you need to allocate memory for b[i] in a for loop as below
// cols and rows are input by user or other parts of program.
int **b;
b = malloc(sizeof(int*) * rows);
for(int i=0; i<rows; i++){
b[i] = malloc(sizeof(int) * cols);
}
The explanation for this is that b is an array of pointers to int. In each element of b you allocate an array of int. This gives you a 2D array.
If you want a rectangular (not jagged array), it's most efficient to allocate all the cells as a single block, then the row pointers can all point into that block:
#include <stdlib.h>
int **make_array(size_t height, size_t width)
{
/* assume this multiplication won't overflow size_t */
int *cells = malloc((sizeof *cells) * height * width);
int **rows = malloc((sizeof *rows) * height);
if (!rows || !cells) {
free(cells);
free(rows);
return 0;
}
/* now populate the array of pointers to rows */
for (size_t row = 0; row < height; ++row) {
rows[row] = cells + width * row;
}
return rows;
}
This also makes deallocation much simpler, as we no longer need a loop:
void free_array(int **a)
{
if (!a) return;
free(a[0]);
free(a);
}

Erros in dynamically allocated array in C

I am trying to dynamically allocate a 2D array, put some values, and print output. However it seems that I am making mistake in getting input to program in atoi() function.
Basically when we assign a static 2D array, we declare it as say int a [3][3]. So 3*3 units if int, that much memory gets allocated. Is same thing holds for allocating dynamic array as well?
Here is my code:
#include<stdio.h>
#include<stdlib.h>
int main(int arg,char* argv)
{
int rows = atoi(argv[1]);
int col = atoi(argv[2]);
int rows =3;
int col=3;
int i,j;
int (*arr)[col] = malloc(sizeof (*arr)*rows);
int *ptr = &(arr[0][0]);
int ct=1;
for (i=0;i<rows;i++)
{
for(j=0;j<col;j++)
{
arr[i][j]=ct;
ct++;
}
}
printf("printing array \n");
for (i=0;i<rows;i++)
{
for(j=0;j<col;j++)
{
printf("%d \t",arr[i][j]);
}
printf("\n");
}
free(arr);
return (0);
}
Program crashes in runtime. Can someone comment?
Try to change the third line to:
int main(int arg,char **argv)
The common method to use dynamic matrices is to use a pointer to pointer to something, and then allocate both "dimensions" dynamically:
int **arr = malloc(sizeof(*arr) * rows);
for (int i = 0; i < rows; ++i)
arr[i] = malloc(sizeof(**arr) * col);
Remember that to free the matrix, you have to free all "rows" in a loop first.
int rows = atoi(argv[1]);
int col = atoi(argv[2]);
int rows =3;
int col=3;
int i,j;
You are defining rows and col twice.... that would never work!
With traditional C, you can only have the array[][] structure for multiple dimension arrays work with compile time constant values. Otherwise, the pointer arithmetic is not correct.
For dynamically sized multi dimensional arrays (those where rows and cols are determined at runtime), you need to do additional pointer arithmetic of this type:
int *a;
int rows=3;
int cols=4;
a = malloc(rows * cols * sizeof(int));
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j)
a[i*rows + j] = 1;
free(a);
Alternatively, you can use double indirection and have an array of pointers each pointing to a one dimensional array.
If you are using GCC or any C99 compiler, dynamic calculation of multiple dimension arrays is simplified by using variable length arrays:
// This is your code -- simplified
#include <stdio.h>
int main(int argc, const char * argv[])
{
int rows = atoi(argv[1]);
int col = atoi(argv[2]);
// you can have a rough test of sanity by comparing rows * col * sizeof(int) < SIZE_MAX
int arr[rows][col]; // note the dynamic sizing of arr here
int ct=1;
for (int i=0;i<rows;i++)
for(int j=0;j<col;j++)
arr[i][j]=ct++;
printf("printing array \n");
for (int i=0;i<rows;i++)
{
for(int j=0;j<col;j++)
{
printf("%d \t",arr[i][j]);
}
printf("\n");
}
return 0;
} // arr automatically freed off the stack
With a variable length array ("VLA"), dynamic multiple dimension arrays in C become far easier.
Compare:
void f1(int m, int n)
{
// dynamically declare an array of floats n by m size and fill with 1.0
float *a;
a = malloc(m * n * sizeof(float));
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
a[i*n + j] = 1.0;
free(a);
}
With VLA you can write to do the same:
void f2(int m, int n)
{
// Use VLA to dynamically declare an array of floats n by m size and fill with 1.0
float a[m][n];
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
a[i][j] = 1.0;
}
Be aware that unlike malloc / free VLA's handling of requesting a size larger than what is available on the stack is not as easily detected as using malloc and testing for a NULL pointer. VLA's are essentially automatic variables and have similar ease and restrictions.
VLA's are better used for smaller data structures that would be on the stack anyway. Use the more robust malloc / free with appropriate detection of failure for larger data structures.
If you are not using a fairly recent vintage C compiler that supports C99 -- time to get one.

Allocate a 2d array in C with one dimension fixed

I want to dynamically allocate 1 dimension of a 2D array (the other dimension is given). Does this work:
int NCOLS = 20;
// nrows = user input...
double *arr[NCOLS];
arr = (double *)malloc(sizeof(double)*nrows);
and to free it:
free(arr)
Not quite -- what you've declared is an array of pointers. You want a pointer to an array, which would be declared like this:
double (*arr)[NCOLS];
Then, you'd allocate it like so:
arr = malloc(nrows * sizeof(double[NCOLS]));
It can then be treated as a normal nrows by NCOLS 2D array. To free it, just pass it to free like any other pointer.
In C, there's no need to cast the return value of malloc, since there's an implicit cast from void* to any pointer type (this is not true in C++). In fact, doing so can mask errors, such as failing to #include <stdlib.h>, due to the existence of implicit declarations, so it's discouraged.
The data type double[20] is "array 20 of double, and the type double (*)[20] is "pointer to array 20 of double". The cdecl(1) program is very helpful in being able to decipher complex C declarations (example).
An example:
#include <stdio.h>
#include <stdlib.h>
#define COLS 2
void func(int (**arr)[COLS], int rows)
{
int i, j;
*arr = malloc(sizeof(int[COLS]) * rows);
printf("Insert number: \n");
for(i = 0; i < rows; i++)
for(j = 0; j < COLS; j++)
scanf("%d", &(*arr)[i][j]);
for(i = 0; i < rows; i++)
for(j = 0; j < COLS; j++)
printf("%d\n", (*arr)[i][j]);
}
int main(void)
{
int (*arr)[COLS];
func(&arr, 2);
free(arr);
return 0;
}
You have to allocate a new array for each element (each element is a pointer to an array) on the first dimension. You can use a loop for that:
for(i = 0; i < NCOLS; i++)
arr[i] = (double *)malloc(sizeof(double)*nrows);
Do the same to free.

How to pass a 2D dynamically allocated array to a function?

I have a 2 dimensional array dynamically allocated in my C code, in my function main. I need to pass this 2D array to a function. Since the columns and rows of the array are run time variables, I know that one way to pass it is :
-Pass the rows and column variables and the pointer to that [0][0] element of the array
myfunc(&arr[0][0],rows,cols)
then in the called function, access it as a 'flattened out' 1D array like:
ptr[i*cols+j]
But I don't want to do it that way, because that would mean a lot of change in code, since earlier, the 2D array passed to this function was statically allocated with its dimensions known at compile time.
So, how can I pass a 2D array to a function and still be able to use it as a 2D array with 2 indexes like the following?
arr[i][j].
Any help will be appreciated.
See the code below. After passing the 2d array base location as a double pointer to myfunc(), you can then access any particular element in the array by index, with s[i][j].
#include <stdio.h>
#include <stdlib.h>
void myfunc(int ** s, int row, int col)
{
for(int i=0; i<row; i++) {
for(int j=0; j<col; j++)
printf("%d ", s[i][j]);
printf("\n");
}
}
int main(void)
{
int row=10, col=10;
int ** c = (int**)malloc(sizeof(int*)*row);
for(int i=0; i<row; i++)
*(c+i) = (int*)malloc(sizeof(int)*col);
for(int i=0; i<row; i++)
for(int j=0; j<col; j++)
c[i][j]=i*j;
myfunc(c,row,col);
for (i=0; i<row; i++) {
free(c[i]);
}
free(c);
return 0;
}
If your compiler supports C99 variable-length-arrays (eg. GCC) then you can declare a function like so:
int foo(int cols, int rows, int a[][cols])
{
/* ... */
}
You would also use a pointer to a VLA type in the calling code:
int (*a)[cols] = calloc(rows, sizeof *a);
/* ... */
foo(cols, rows, a);
You really can't do this without changing a lot of code. I suggest to wrap this in a structure which contains the limits and then use regexp search'n'replace to fix the accesses.
Maybe use a macro like AA(arr,i,j) (as in Array Access) where arr is the structure.
As far as I know, all you can pass to a function is a pointer to the first element of an array. When you pass an actual array to a function, it is said that "the array decays into a pointer" so no information about the size(s) of the pointed array remains.
A reference to an object of type array-of-T which appears in an expression decays (with three exceptions) into a pointer to its first element; the type of the resultant pointer is pointer-to-T.
I believe you will be able to find more information about this on the C FAQ.
Numerical recipes in C (a book dealing mostly in matrices) suggests a way to do this cleanly and still deal with 2D matrices. Check out the section 1.2 "Matrices and 2D arrays" and the method convert_matrix().
Essentially what you need is to allocate a set of pointers to point to your row vectors. And pass this to your function along with the number of rows and columns.
A 2-d array in C is just an array of arrays. Here ya go:
void with_matrix(int **matrix, int rows, int cols) {
int some_value = matrix[2][4];
}
int main(int argc, char **argv) {
int **matrix;
... create matrix ...
with_matrix(matrix, rows, cols);
}
int cols = 4;
int rows = 3;
char** charArray = new char*[rows];
for (int i = 0; i < rows; ++i) {
charArray[i] = new char[cols];
}
// Fill the array
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
charArray[i][j] = 'a';
}
}
// Output the array
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cout << charArray[i][j];
}
cout << endl;
}

Resources