I have seen the following declaration of two dimensional array.
int arr[][3] = { {1,2,3}, {4,5,6}};
My question is how can I allocate following multidimensional array in run time based on user input of first dimension?
#define M 10
#define N 15
int arr[][M][N]
Start by declaring a pointer suitable for accessing the array:
int (*array)[M][N];
Then allocate memory for the array based on the user input:
array = malloc(P * sizeof(*array)); // P is the value obtained from the user
Then use the pointer as if it was a 3D array:
array[x][y][z] = 42;
Don't forget to free the memory when you're done with it.
C allows variable-length arrays. So after reading the first dimension from the user, you can declare the array with that size.
int n;
printf("How big is it? ");
scanf("%d", &n);
int arr[n][M][N];
Related
I can initialize a one dimensional array in c with or without initializing its size:
int x[] = {1,2,3,4,5};
int y[5] = {1,2,3,4,5};
But, when I try to do the same for a two dimensional array such as
int x[][] = {{1,2,3},
{4,5,6}};
I get an error: array type has incomplete element type. The same error occurs if I declare and initialize the array on different lines.
However, I can initialize it while stating the size:
int x[2][3] = {{1,2,3},
{4,5,6}};
There is no error with this one.
My question is, is it possible to initialize a multi dimensional array without first initializing its size? I ask this because for an eventual project, I need to be able to declare arrays and initialize them later, and their size will not be known when compiling.
is it possible to initialize a multi dimensional array without first initializing its size?
No, not in the way you are proposing or anything similar to that.
I need to be able to declare arrays and initialize them later, and they will have dynamic sizes.
If the size is unknown at compile time, you should allocate the array using a = malloc(x * y * sizeof(value_t)). Then index into it like a[i + j*y].
Is it possible to initialize a multi dimensional array without first initializing its size?
=> No, it is not possible.
The thing possible is that you take the size of the array and then allocate memory using calloc.
I'm asking you to use calloc because this way all the array elements will be initially initialized as 0.
Now, use of calloc will be applied as:
Assuming you want 2D array, so you take variable row and column as input from the user.
Then use,
int *x;
x = calloc( ( row * column), sizeof(datatype) );
In this case the datatype would be int.
In short code would appear as :
int row, column, *x;
/* TAKING INPUT FROM THE USER */
printf("\n\t Enter the number of rows : ");
scanf("%d", &row);
printf("\n\t Enter the number of columns : ");
scanf("%d", &column);
/* DYNAMICALLY ALLOCATING MEMORY TO x USING calloc */
x = calloc( (row * column), sizeof(int));
I hope this code solves your problem.
I have one more thing to share with you.
In your this line of code :
int x[][] = {{1,2,3},
{4,5,6}};
This initialization is just missing one thing and that thing is mention of column size and otherwise code is correct.
So, Correction to your code :
int x[][3] = {{1,2,3},
{4,5,6}};
This would work fine.
Keep on trying! These type of things can only be known while practicing.
Happy Coding!
Yes, but you're missing a comma:
int x[2][3] = {{1,2,3},
{4,5,6}};
All array elements (even inner arrays) need to be comma-separated
When allocating array in C, what is the difference between the below two -
int n;
scanf("%d",&n);
int array[n];
And
int *array = (int *)malloc(sizeof(int)*n);
I know that the second one is dynamic allocation of array, which gets allocated from heap. But I am unable to figure out how the first method works. Does it allocate array on runtime, after getting the value for n? And which one should I be using?
This question already has answers here:
A different way to malloc a 2D array?
(3 answers)
Freaky way of allocating two-dimensional array?
(3 answers)
Closed 6 years ago.
Every time I allocate the memory for a 2D array first I create an array of int** and then with a for I allocate the memory for each element.
For example:
int ** arr = malloc(N*sizeof(int *));
for(i=0; i< N; i++) arr[i] = malloc(M*sizeof(int));
Wouldn't be possible allocate the memory like:
int ** arr = malloc(N*sizeof(int[M]));
or
int ** arr = malloc(sizeof(int[N][M]));
in order to avoid the for?
like this : int (*arr)[M] = malloc(sizeof(int[N][M]));
arr is pointer to int[M].
use like arr[0][M-1];
and free(arr);
int ** arr = malloc(N*sizeof(int[M]));
is incorrect C code, if you simulate it by allocating once
int *arr = malloc(N*M*sizeof(int));
and access it by
arr[i*M + j],
this is an analog to arr[I][j] in your first case.
You have a "pointer to pointer". That cannot represent a 2D array.
The correct declaration of a pointer to a 2D array is
// number of elements in one row
#define COLS 10
// number of rows
#define ROWS 20
int (*array)[COLS]; // mind the parenthesis!
That makes array a pointer to array of COLS ints. The type is `int (*)[COLS], btw. but you don't need the type, see below.
To allocate the array you should then use the standard allocation for a 1D array:
array = malloc(sizeof(*array) * ROWS); // COLS is in the `sizeof`
array = malloc(sizeof(int[ROWS][COLS])); // explicit 2D array notation
Which variant to use is personal style. While the first contains no redundancy (consider you change the declaration of array to use INNER instead of COLS or the element-type to float). The second is more clear at a fist glance, but more prone to errors when modifying the declaration of array.
To free:
free(array);
i want to create a matrix in C, but size of the matrix must be determine by user.There is my code.
int row1,column1;
printf("Please enter number of rows in first matrix: ");
scanf("%d",&row1);
printf("Please enter number of columns in first matrix: ");
scanf("%d",&column1);
int M1[row1][column1];
i get errors with row1 and column1(in the last line).What is the correct way of taking size of a matrix from an user?
You have to dynamically allocate the array as you don't know the size at compile time.
My hint: use a single array it's much simpler:
int M1[] = new int[row1 * column1];
Then address it as
M1[column + line * row1];
If you absolutely need a 2D matrix, refer to this question: How do I declare a 2d array in C++ using new?
And don't forget to delete[] properly your array.
Related: dynamic allocating array of arrays in C
First allocate an array of pointers:
M1 = (int**)malloc(row1 * sizeof(int*));
And then point each to another array.
for(i = 0; i < row1; i++)
M1[i] = (int*)malloc(column1 * sizeof(int));
In c to create matrix of user defined size you need to use dynamic allocation using malloc or alloca(). you can read this link to get information on creating arrays of user defined size in c
This is because you cannot initialize an array with array length as a variable. Declare a pointer and use malloc to dynamically allocate the array.
int row1,column1;
printf("Please enter number of rows in first matrix: ");
scanf("%d",&row1);
printf("Please enter number of columns in first matrix: ");
scanf("%d",&column1);
int **arr;
//allocate the memory
arr=malloc(sizeof(int*)*row1);
int i;
for (i=0;i<row1;i++)
*(arr+i)=malloc(sizeof(int)*column1);
//do what you want to do
//free the memory
for (i=0;i<row1;i++)
free(*(arr+i));
free(arr);
I am doing an assignment for class and I thought I would bug you all with a question:
So the purpose of the program is for the user to enter the size of the array and then initialize it with some data. Max size is 20. My issue is that the array crashes when the sets the size beyond 14 and tries to initialize it. So forexample, if it sets the size as 20, it accepts it, but when I try to initialize it, it crashes. I have no idea what I am doing. your help is much appreciated.
Thank you very much,
Essi
int main ()
{
int sizeOfArray = 0; //size Of Array
float myArray[sizeOfArray];
//I have a piece a line or two of code that asks the user for the size of the
array
printf("Let's Initialize an array of size %d!!\n", sizeOfArray);
do
{
printf("Enter array element %d : ", initCounter+1);
myArray[initCounter] = userInitArray();
initCounter++;
}while (initCounter < sizeOfArray);
}
float userInitArray()
{
float num;
scanf("%f", &num);
return num;
}
These two lines
int sizeOfArray = 0; //size Of Array
float myArray[sizeOfArray];
Create an empty array. So whatever you try to store in this array later on is access out of bounds and invokes undefined behavior. The fact that your program crashes on 14th call is simply luck. It could have crashed on the first one just as well.
int sizeOfArray = 0; //size Of Array
float myArray[sizeOfArray];
Your array is created here with a size of zero. It doesn't magically expand when you later increase sizeOfArray. You need to get the size variable set first (from your 'line or two of code' user input) then create the array based on that.
You may also want to impose some sensible upper limit on your array size so you don't blow up your stack when trying, for example, to create a one-billion-entry array :-)
You have a (variable-length) array of size zero. You need to first ask for the size, and then allocate the array. Otherwise any attempts to assign to array elements would result in undefined behaviour.
You could do :
int sizeOfArray; //size Of Array
printf("tell me the size of the array");
scanf("%d",&sizeOfArray);
float myArray[sizeOfArray]; // not a good practice
The right way to do it would be:
int sizeOfArray; //size Of Array
float *myArray;
printf("tell me the size of the array");
scanf("%d",&sizeOfArray);
myArray=malloc(sizeof(float)*sizeOfArray);
You may use the pointer as a common array then.
and call like this: myArray[3] = doSomething();
EDIT Note that since you already know the max size you could avoid doing dynamic allocations listed above:
#Define MAXSIZE 20
int main ()
{
int sizeOfArray; //size Of Array
float myArray[MAXSIZE];
printf("tell me the size of the array\n");
scanf("%d",&sizeOfArray);
printf("\nLet's Initialize an array of size %d!!\n", sizeOfArray);
do
{
printf("Enter the element at myArray[%d] : ", initCounter+1);
myArray[initCounter] = userInitArray();
initCounter++;
}while (initCounter < sizeOfArray);
}
float userInitArray()
{
float num;
scanf("%f", &num);
return num;
}
Probably this last option is what your teacher is actually looking for.
You need to read sizeOfArray before you allocate myArray dynamically like this:
float * myArray = malloc(sizeOfArray * sizeof(float));
This is allocating sizeof(float) * sizeOfArray bytes of memory on heap and assigning address of allocated memory to myArray.
This is maybe hard to understand about arrays in C, they are really just pointers into memory - in your program the array myArray is allocated statically on stack and is of size 0. You cannot add any elements to it or assign to any index, it will not grow, its forewer 0 float elements long. Best thing that can happen to your program in this case is that it will crash. Worst case, it will not crash and strange things will happen;
You really should read something about memory allocation/management in C.
I think you forget to add function prototype in the beginning of your program (before main).
And also
int sizeOfArray = 0; //size Of Array
float myArray[sizeOfArray];
is wrong.
As you are using variable length array (valid in C99), you can do it as
int sizeOfArray; //size Of Array
printf("Let's Initialize an array of size %d!!\n", sizeOfArray);
float myArray[sizeOfArray];
dynamic arrays are not supported in C or C++.
Change your array to:
float* myAraray;
//later when you have the size , allocate it:
myArray = (float*)malloc(arrSize * sizeof(float));