Erros in dynamically allocated array in C - 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.

Related

Can I create a dynamic 2D array in C like this?

Can I use
size_t m, n;
scanf ("%zu%zu", &m, &n);
int (*a)[n] = (int (*)[n])calloc (m * n, sizeof (int));
to create a dynamic 2D array in C, whose size of rows and columns can be modified by function realloc during runtime?
Also you can use pointer-to-pointer-to-int and alloc first array for "pointers to lines" and then init all items by allocating memory for "arrays of int".
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
size_t m, n;
scanf("%zu%zu", &m, &n);
int **a = (int **)calloc(m, sizeof(int*));
size_t i, j;
for (i = 0; i < m; i++) {
a[i] = (int *)calloc(n, sizeof(int));
}
/// Work with array
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
a[i][j] = i+j;
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}
Such approach allows to make realloc later
This record
int (*a)[n] = (int (*)[n])calloc (m * n, sizeof (int));
is correct provided that the compiler supports variable length arrays.
It may be written also like
int (*a)[n] = calloc ( 1, sizeof ( int[m][n] ) );
On the other hand, there is a problem when you will use realloc and the number of columns must be changed. This can result in losing elements in the array in its last row because C memory management functions know nothing about types of objects for which the memory is allocated. They just allocate extents of memory of required sizes.
Otherwise if the compiler does not support variable length arrays you will need to allocate array of pointers and for each pointer an array of integers. This approach is more flexible in sense that you can reallocate separately columns and rows.
Can I create a dynamic 2D array in C like this?
int (*a)[n] = (int (*)[n])calloc (m * n, sizeof (int));
Yes.
Cleaner as int (*a)[n] = calloc(m, sizeof a[0]);
Can I use int (*a)[n] = .... to create a dynamic 2D array in C, whose size of rows and columns can be modified by function realloc during runtime?
No. Once an array size of a is defined, (n in this case), the size can not change.
Instead consider allocating an array of arrays
// Error checking omitted for brevity
int **a2 = malloc(sizeof a2 * rows);
for (r = 0; r < rows; r++) {
a2[r] = malloc(sizeof a2[0] * cols);
}

different ways to declare a matrix c

I don't really understand why method 1 works but not method 2. I don't really see why it works for characters and not an int.
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
/// WORK (METHODE 1)
char **string_array = malloc(sizeof(char **) * 10);
string_array[0] = "Hi there";
printf("%s\n", string_array[0]); /// -> Hi there
/// DOES NOT WORK (METHODE 2)
int **int_matrix = malloc(sizeof(int **) * 10);
int_matrix[0][0] = 1; // -> Segmentation fault
/// WORK (METHODE 3)
int **int_matrix2 = malloc(sizeof(int *));
for (int i = 0; i < 10; i++)
{
int_matrix2[i] = malloc(sizeof(int));
}
int_matrix2[0][0] = 42;
printf("%d\n", int_matrix2[0][0]); // -> 42
}
In terms of the types, you want to allocate memory for the type "one level up" from the pointer you're assigning it to. For example, an int pointer (an int*), points to one or more ints. That means, when you allocate space for it, you should allocate based on the int type:
#define NUM_INTS 10
...
int* intPtr = malloc(NUM_INTS * sizeof(int));
// ^^ // we want ints, so allocate for sizeof(int)
In one of your cases, you have a double int pointer (an int**). This must point to one or more int pointers (int*), so that's the type you need to allocate space for:
#define NUM_INT_PTRS 5
...
int** myDblIntPtr = malloc(NUM_INT_PTRS * sizeof(int*));
// ^^ "one level up" from int** is int*
However, there's an even better way to do this. You can specify the size of your object it points to rather than a type:
int* intPtr = malloc(NUM_INTS * sizeof(*intPtr));
Here, intPtr is an int* type, and the object it points to is an int, and that's exactly what *intPtr gives us. This has the added benefit of less maintenance. Pretend some time down the line, int* intPtr changes to int** intPtr. For the first way of doing things, you'd have to change code in two places:
int** intPtr = malloc(NUM_INTS * sizeof(int*));
// ^^ here ^^ and here
However, with the 2nd way, you only need to change the declaration:
int** intPtr = malloc(NUM_INTS * sizeof(*intPtr));
// ^^ still changed here ^^ nothing to change here
With the change of declaration from int* to int**, *intPtr also changed "automatically", from int to int*. This means that the paradigm:
T* myPtr = malloc(NUM_ITEMS * sizeof(*myPtr));
is preferred, since *myPtr will always refer to the correct object we need to size for the correct amount of memory, no matter what type T is.
Others have already answered most of the question, but I thought I would add some illustrations...
When you want an array-like object, i.e., a sequence of consecutive elements of a given type T, you use a pointer to T, T *, but you want to point to objects of type T, and that is what you must allocate memory for.
If you want to allocate 10 T objects, you should use malloc(10 * sizeof(T)). If you have a pointer to assign the array to, you can get the size from that
T * ptr = malloc(10 * sizeof *ptr);
Here *ptr has type T and so sizeof *ptr is the same as sizeof(T), but this syntax is safer for reasons explained in other answers.
When you use
T * ptr = malloc(10 * sizeof(T *));
you do not get memory for 10 T objects, but for 10 T * objects. If sizeof(T*) >= sizeof(T) you are fine, except that you are wasting some memory, but if sizeof(T*) < sizeof(T) you have less memory than you need.
Whether you run into this problem or not depends on your objects and the system you are on. On my system, all pointers have the same size, 8 bytes, so it doesn't really matter if I allocate
char **string_array = malloc(sizeof(char **) * 10);
or
char **string_array = malloc(sizeof(char *) * 10);
or if I allocate
int **int_matrix = malloc(sizeof(int **) * 10);
or
int **int_matrix = malloc(sizeof(int *) * 10);
but it could be on other architectures.
For your third solution, you have a different problem. When you allocate
int **int_matrix2 = malloc(sizeof(int *));
you allocate space for a single int pointer, but you immediately treat that memory as if you had 10
for (int i = 0; i < 10; i++)
{
int_matrix2[i] = malloc(sizeof(int));
}
You can safely assign to the first element, int_matrix2[0] (but there is a problem with how you do it that I get to); the following 9 addresses you write to are not yours to modify.
The next issue is that once you have allocated the first dimension of your matrix, you have an array of pointers. Those pointers are not initialised, and presumably pointing at random places in memory.
That isn't a problem yet; it doesn't do any harm that these pointers are pointing into the void. You can just point them to somewhere else. This is what you do with your char ** array. You point the first pointer in the array to a string, and it is happy to point there instead.
Once you have pointed the arrays somewhere safe, you can access the memory there. But you cannot safely dereference the pointers when they are not initialised. That is what you try to do with your integer array. At int_matrix[0] you have an uninitialised pointer. The type-system doesn't warn you about that, it can't, so you can easily compile code that modifies int_matrix[0][0], but if int_matrix[0] is pointing into the void, int_matrix[0][0] is not an address you can safely read or write. What happens if you try is undefined, but undefined is generally was way of saying that something bad will happen.
You can get what you want in several ways. The closest to what it looks like you are trying is to implement matrices as arrays of pointers to arrays of values.
There, you just have to remember to allocate the arrays for each row in your matrix as well.
#include <stdio.h>
#include <stdlib.h>
int **new_matrix(int n, int m)
{
int **matrix = malloc(n * sizeof *matrix);
for (int i = 0; i < n; i++)
{
matrix[i] = malloc(m * sizeof *matrix[i]);
}
return matrix;
}
void init_matrix(int n, int m, int **matrix)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
matrix[i][j] = 10 * i + j + 1;
}
}
}
void print_matrix(int n, int m, int **matrix)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main(void)
{
int n = 3, m = 5;
int **matrix = new_matrix(n, m);
init_matrix(n, m, matrix);
print_matrix(n, m, matrix);
return 0;
}
Here, each row can lie somewhere random in memory, but you can also put the row in contiguous memory, so you allocate all the memory in a single malloc and compute indices to get at the two-dimensional matrix structure.
Row i will start at offset i*m into this flat array, and index matrix[i,j] is at index matrix[i * m + j].
#include <stdio.h>
#include <stdlib.h>
int *new_matrix(int n, int m)
{
int *matrix = malloc(n * m * sizeof *matrix);
return matrix;
}
void init_matrix(int n, int m, int *matrix)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
matrix[m * i + j] = 10 * i + j + 1;
}
}
}
void print_matrix(int n, int m, int *matrix)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
printf("%d ", matrix[m * i + j]);
}
printf("\n");
}
}
int main(void)
{
int n = 3, m = 5;
int *matrix = new_matrix(n, m);
init_matrix(n, m, matrix);
print_matrix(n, m, matrix);
return 0;
}
With the exact same memory layout, you can also use multidimensional arrays. If you declare a matrix as int matrix[n][m] you will get what amounts to an array of length n where the objects in the arrays are integer arrays of length m, exactly as on the figure above.
If you just write that expression, you are putting the matrix on the stack (it has auto scope), but you can allocate such matrices as well if you use a pointer to int [m] arrays.
#include <stdio.h>
#include <stdlib.h>
void *new_matrix(int n, int m)
{
int(*matrix)[n][m] = malloc(sizeof *matrix);
return matrix;
}
void init_matrix(int n, int m, int matrix[static n][m])
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
matrix[i][j] = 10 * i + j + 1;
}
}
}
void print_matrix(int n, int m, int matrix[static n][m])
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main(void)
{
int n = 3, m = 5;
int(*matrix)[m] = new_matrix(n, m);
init_matrix(n, m, matrix);
print_matrix(n, m, matrix);
int(*matrix2)[m] = new_matrix(2 * n, 3 * m);
init_matrix(2 * n, 3 * m, matrix2);
print_matrix(2 * n, 3 * m, matrix2);
return 0;
}
The new_matrix() function returns a void * because the return type cannot depend on the runtime arguments n and m, so I cannot return the right type.
Don't let the function types fool you, here. The functions that take a matrix[n][m] argument do not check if the matrix has the right dimensions. You can get a little type checking with pointers to arrays, but pointer decay will generally limit the checking. The last solution is really only different syntax for the previous one, and the arguments n and m determines how the (flat) memory that matrix points to is interpreted.
The method 1 works only becuse you assign the char * element of the array string_array with the reference of the string literal `"Hi there". String literal is simply a char array.
Try: string_array[0][0] = 'a'; and it will fail as well as you will dereference not initialized pointer.
Same happens in method 2.
Method 3. You allocate the memory for one int value and store the reference to it in the [0] element of the array. As the pointer references the valid object you can derefence it (int_matrix2[0][0] = 42;)

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 scanf to fill out a multidimensional array (C language)

I was wondering how to properly use scanf to fill out a multidimensional array.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char * argv[]) {
int n; //number of rounds
int* sArray; //multidimensional array that holds the scores of both players
int i;
scanf("%d", &n);
sArray = (int*) calloc (n * 2, sizeof(int));
for(i=0; i<n; i++) {
scanf("%d %d", &sArray[i][1], &sArray[i][2]);
}
return 0;
}
It gives me an error, "Subscripted value is not an array, pointer, or vector." Any help would be much appreciated!
A two dimentional array is defined as follows: int sArray[N][M], but since you wanted to work with the dynamic memory I offer you to take a look at a pointer to pointer at int:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
scanf("%d", &n);
int **sArray;
sArray = (int **)malloc(n * sizeof(int *));
int i;
for(i = 0; i < n; i++)
{
sArray[i] = (int *)malloc(2 * sizeof(int));
scanf("%d %d", &sArray[i][1], &sArray[i][2]);
}
return 0;
}
Don't forget to clean-up after you are done with the array.
As mentioned in the commentaries, You don't need to cast the result of malloc if you work with pure c. I did this because my c++ compiler refused to compile it without this cast.
You might need to check errors during a dynamic allocation of the array. Read more here
There are already a lot of good answers here on how to define your dynamic 2D array. But this variant was not yet mentionned, so I put it for the records.
As the last dimension of your array is fixed, you could define your 2D array as follows:
int (*sArray)[2]; //multidimensional array that holds the scores of both players
...
sArray = (int(*)[2]) calloc (n, sizeof(int)*2); // self explaining
In this way, all the elements will be stored contiguously (each n element of the allocated array, is 2 contiguous integers), without the need for an array to arrays.
The rest of your code remains identical. Except that you shoud address sArray[i][0] and ..[1] instead of [1] and [2] and free memory at the end. In C array indexing starts always from 0 and goes to size-1.
Of course, this approach is strictly limited to 2D arrays where the last dimension is fixed.
Live demo with addressing
Usually to fill a bidimensional array you will use two nested for loops.
For example :
int array[2][3] = {0};
for (i = 0; i < 2; i++)
for (k = 0; k < 3; k++)
scanf("%d", &array [i][k]);
You could do this too:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char * argv[]) {
int n; //number of rounds
int** sArray = malloc(2 * sizeof(int*)); //multidimensional array that holds the scores of both players
scanf("%d", &n);
sArray[0] = (int*)calloc(n , sizeof(int));
sArray[1] = (int*)calloc(n , sizeof(int));
int i;
for (i = 0; i < n; i++) {
scanf("%d %d", &sArray[0][i], &sArray[1][i]);
}
free(sArray[0]);
free(sArray[1]);
free(sArray);
return 0;
}

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.

Resources