I came across a problem where i need to declare a 2D array dynamically.
The number of rows were known(i.e 2) while the number of columns are to taken as input.
I used this technique :
cin>>size;
int **outer = new int*[2];
int outer[0] = new int[size];
int outer [1] = new int[size];
But this gave an error : conflicting declaration 'int outer [0]'
Than i fixed the problem by changing my code to :
cin>>size; // size of the column
int **outer = new int*[2];
for(int i=0;i<2;i++)
outer[i] = new int[size];
So, i want to know why can't i declare 2D array like as that of 1st , bcz i am declaring it after i have declared and defined the size.
With
int outer[0] = ...;
you define a completely new variable named outer, as an array of zero elements.
Plain assignment seems to be what you want:
outer[0] = new int[size];
outer[1] = new int[size];
And I really recommend you don't use your own manual memory and pointer handling. First fix would be to realize that outer doesn't need to be a pointer but an array, as in
int* outer[2] = {
new int[size],
new int[size]
};
Then eliminating pointers altogether using std::vector you could do it as
std::vector<int> outer[2] = {
std::vector<int>(size),
std::vector<int>(size)
};
You should also consider replacing the C-style array with std::array:
std::array<std::vector<int>, 2> outer = {
std::vector<int>(size),
std::vector<int>(size)
};
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
public class JAVA_Guevarra {
public static void main(String[] args) {
//These are the variables
double empBasicPay[] = {4000,5000,12000,6000,7500};
double empHousingAllow[] = new double[5];
int i;
//This program computes for the payment of the employees
for(i=0; i<5; i++){
empHousingAllow[i] = 0.2 * empBasicPay[i];
//This loop statement gets 20% of the employee basic payment
}
System.out.println("Employee Basic and House Rental Allowance");
for(i = 0; i<5; i++){
System.out.println(empBasicPay[i] + " " + empHousingAllow[i]);
//This prints out the final output of the first loop statement
}
}
}
What does the new double[5] do in this statement?
it's not just new double, it is new double[5] which create an array for maximum 5 doubles
as oracle doc explain it well (https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html)
// declares an array of integers
int[] anArray;
// allocates memory for 10 integers
anArray = new int[10];
// initialize first element
anArray[0] = 100;
// initialize second element
anArray[1] = 200;
so double empHousingAllow[] = new double[5]; allocate memory for an array of five doubles
The new keyword in Java is used to create objects. In this case, the object which is being created is an array containing five doubles.
You might want to have a look at this question, which describes declaration of arrays in greater detail.
Actually the concept required size when you define an array, later you can not change the size.
You can not assign value directly to the memory block like
double d[5];
d[0] = 10.05;
you need to create memory block with specific type.
That's why you need to define an array in that manner.
double d[] = new double[5]
Or
double d[5];
d[0] = new double like that.
then you can add the value to that block.
i have an array with an initial size
int size = 5; //initial size ofwordsArray
wfpPointer wordsArray = new WordFrequencyPair[size];
where wfpPointer is a typedef for a pointer that points to the adress of a variable of type WordFrequencyPair.
now when i detect that my array is full i call the following function to expand it:
int expandWordsArray(WordFrequencyPair wordsArrayIn[], int currentSize){
int newSize = currentSize * 2;
wfpPointer newArray = new WordFrequencyPair[newSize];
for(int i = 0; i < currentSize; i++)
newArray[i] = wordsArrayIn[i];
delete [] wordsArrayIn;
wordsArrayIn = newArray;
return newSize;
}
the thing is when i write this code in the main without calling the function it works perfectly fine and the array expands. From within the function however my program crashes. Note: eclipse gives me no errors and compiles the program without trouble.
Plz help
Thank you
You are passing the array (that is, a pointer to the first element of the array) by value. The function deletes, the array (using the original value of the pointer), then constructs a new array on the heap and points the local pointer to it.
Meanwhile, back in the calling code (main), the pointer hasn't changed and the old array has been deleted. When you try to dereference the pointer, BOOM!
You should pass the pointer by reference:
int expandWordsArray(WordFrequencyPair *&wordsArrayIn, int currentSize)
I'm modifying existing code for a new project. I was instructed to remove dynamic memory allocation and use static declaration.
There is a variable arrp, earlier it was a double pointer, to which memory will be allocated using malloc and will be accessed as 2D array.
Now i have changed it as pointer to array i.e: char (*arrp)[];
The size of the 2D array to which arrp points to will be known only at runtime. My problem is if size is not declared compiler throws error('char (*)[]' : unknown size)
Please refer the following code, i did something like this
char (*arrp)[]; //This will be from different module,
//I have declared as local variable for our reference
char (*parr)[2];
char arr[3][2];
parr = &(arr[0]);
arrp = (char (*)[])&(arr[0]);
//inside loops for i, j
...
printf("%c",parr[i][j]); // This works fine
printf("%c",arrp[i][j]); // Error :'char (*)[]' : unknown size)
....
//Some code
It not possible to get the size of array when arrp is declared. Is there any way to eliminate this error?
A pointer to an array helps in jumping over whole arrays at a time. ( ie with a single increment ) It does this through the knowledge of the column width of the array to be jumped. So without the knowledge of the column size, I am afraid, your pointer to an array will be of no use to you.
But if you have a modern compiler which supports variable length arrays ( C99 ), then its quite simple
int foo ( int m, int n )
{
int a[m][n];
int (*ptr)[n]=a;
a[0][2] = 78;
printf("%d", ptr[0][2]);
}
I have an array, which is now static. This are the operations I do with it.
Firstly I create a two-dimensional array. Then I fill it in, using cycles. And then I send it to function, where there are also cycles which are used.
Here I 'd like to post some sample code, which is similar to mine.
bool picture[20][20]; //here's my array right now. Pretty ugly. Just for testing.
for (int y=0;y<Height;y++)
{
for (int x=0;x<Width;x++)
{
if (treshold<middle)
{
picture[x][y]=1;
}
else
{
picture[x][y]=0;
}
}
}
//Here's an example of filling an array
leftk = left(picture,widthk, heightk); //That's how I use a function
int left(int picture[200][200],int row,int col)
{
for (int x = 0; x <=row-1; x++)
{
for (int y = 0; y <=col-1 ;y++)
{
if (picture1[x][y]==1)
{
return x;
}
}
}
}
//And that's the function itself
So here I need to switch my array to a dynamic one. That's how I declare my dynamic array
bool** picture=new bool*[size];
for(int i = 0; i < size; ++i)
picture[i] = new bool[size];
//size is just a variable.
As for statically declared cycles, everything is very simple. Sending this array as a parameter to function.
I've already managed to create a dynamic array, it's simple. Then I fill it in with numbers. No problems here too. But I can't understand, how to send an array to function and moreover how to use it there.
Could you give me an exaple of modifying two-dimensional arrays in functions.
Sorry for such a newbie question. Hope someone will help.
By the way, class wrapping would be a bit confusing here, I think.
A function such as:
Process2DArray(int **pArray, int rowCount, int colCount)
Should suffice the needs assuming its a 2D array that is being operated on. Also, consider using std::vector<std::vector<int>> instead of a multidimensional array allocated manually. This approach will help prevent leaks. The second approach also lets you have jagged arrays.
The usual solution is to wrap the array in a class; C doesn't handle
arrays very well, and C++ doesn't have any real support for 2D arrays in
its library either. So you define either:
class Array2D
{
std::vector<double> myData;
int myColumnCount;
int myRowCound;
// ...
};
with accessors which convert the two indexes using i * myColumnCount +
j, or:
class Array2D
{
std::vector<std::vector<double> > myData;
// ...
};
with initialization logic ensure that all of the rows have the same
length. The first is generally simpler and easier to understand; if you
want to increase the number of columns, however, the second is
significantly easier.
You have several options:
an array of arrays. For example, for int would be int **a which should be able to hold n arrays new int *[n], then go with a for through them and initialized them a[i] = new int[elems_per_line]
a "packed" 1D array int *a = new int[n * elems_per_line], where element (i, j) - 0-based is actually a[i * elems_per_line + j].
you can refine point 1, and have the 2D matrix be "curly" - with lines of different lengths, but you'll need an array to hold each length.
Hope this helps.