i need to take size of the matrix from user - c

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);

Related

Double dimension array definition in C [duplicate]

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

C - multidimensional array memory allocation based on user input

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];

Declaring an 2 dimensional array with size according to input

Say, I want an array of words that is of max length 20. I get the number of words to be stored from user input. What is the most memory efficient way to declare the above array?
I could do something like this, but I guess its not very memory efficient?
char wordArray[1000][20];
That is I want "1000" to varies accordingly to user's input. And I can't do this.
int main()
{
int size;
printf("Enter size: ");
scanf("%d", &size);
char wordArray[size][20];
}
Generally stack size is small and you can't allocate such a big amount of memory on stack. Doing so will result in stack overflow. You need dynamic allocation.
int size;
printf("Enter size: ");
scanf("%d", &size);
char **wordArray = malloc(size*sizeof(char *));
for(int i = 0; i < size; i++)
wordArray[i] = malloc(20);
Call free to deallocate.
But, note that this will allocate defragmented memory instead of continuous unlike as in case of 2D array. To get continuous memory allocation you can use pointer to array as
int (*wordArray)[20] = malloc(size * sizeof(*wordArray));
and access the element as wordArray[i][j].
For more detailed explanation read c-faq 16.6: How can I dynamically allocate a multidimensional array?
Nope, it is not, because you're imposing an allocation of 100000 times sizeof(char) of memory. And no, you can't do as you wrote here, because during the compile-time the size of array is unknown, so space cannot be allocated. You could do it using malloc.

initializing an array using a function in C

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));

Getting a user to input multiple values into a calloc array, C

trying to get my head around memory allocation and pointers in the C programming language.
If I allocate a space in memory for an array like so:
int *array = (int*) calloc(10, sizeof(int));
Can I then get the user to input multiple values to go into that array like this?
printf("Please enter values:\n");
scanf("%d", &*array);
Further more does the first line of code create a space in memory for an array and a pointer to that space. ie can I later point to a number in that array using *array? If this is not the case do I need some code along the lines of:
int *ptr;
int array;
ptr = array;
Quite new to programming so I apologize if my logic is not clearly shown. Also thanks in advance for any help.
Rus
You cannot do it without a loop. Here is what you can do:
for (int i = 0 ; i != 10 ; i++) {
printf("Please enter value for element %d:\n", i+1);
scanf("%d", &array[i]);
}
does the first line of code create a space in memory for an array and a pointer to that space?
Yes, it does. In C you do not need to cast the results of malloc/calloc/realloc, so you can re-write that line like this:
int *array = calloc(10, sizeof(int));

Resources