I have
main(){...
float **tree;
//How to set some values here for e.g. If I want tree to be a 15x2 array of some values?
reprVectorsTree *r1 = new reprVectorsTree(tree,8,2);
...}
reprVectorsTree(float **tree, int noOfReprVectors, int dimensions)
{.....
How to use malloc here so that I can set some data inside the tree array?
To allocate memory for tree, try something like:
float** tree;
tree = (float**)malloc(15 * sizeof(float*));
for(i = 0; i < 15; i++)
tree[i] = (float*)malloc(2 * sizeof(float));
Now you can set values:
for(i = 0; i < 15; i++)
for(j = 0; j < 2; j++)
tree[i][j] = 2;
Don't forget to free it later, although I don't understand why you are combining new and malloc together?
I guess it's the tree variable you want to allocate for.
You can do like this:
float **tree;
// Allocate 15 "arrays"
tree = new float*[15];
for (int i = 0; i < 15; i++)
{
// Allocate a new "array" of two floats
tree[i] = new float[2];
// Fill the newly allocated floats with "random" data
tree[i][0] = 1.0;
tree[i][1] = 2.0;
}
However, if it's possible I would recommend that you change the reprVectorsTree object to accept std::vector< std::vector< float > > instead.
Related
I was following a tutorial here. I came across the following lines of code.
double** pvalue = NULL; // Pointer initialized with null
pvalue = new double [3][4]; // Allocate memory for a 3x4 array
When I compiled it, it is throwing an error
"cannot convert 'double (*)[4]' to 'double**' in assignment"
Is the code invalid? or I'm doing something wrong.Also, please, if possible, describe how could I declare pointer to multi dimension array?
You can not do it. double [3][4]; allocates a flat memory of 3 arrays double[4]. The tutorial has the error.
using d4 = double [4];
// or typedef double d4[4];
d4* pvalue = nullptr;
pvalue = new double [3][4];
delete[] pvalue;
This pvalue = new double [3][4]; is not correct. Find how to allocate memory for 2D array using new. May be you want like below.
int main(void) {
double** pvalue = NULL;
/* first allocate for pvalue */
pvalue = new double *[3];
for(int col = 0; col < 3 ; col++ )
/* allocate for each palue element */
pvalue[col] = new double [4];
return 0;
}
Once done, don't forget to free the dynamically allocated memory by calling delete.
You can't do this. If you must allocate memory by yourself, try:
double** pt=nullptr;
pt=new double[3];
for(std::size_t i=0;i<3;++i)
pt[i]=new double[4];
the deletion is a reverse process of allocation.
And one thing you need to notice is that you shouldn't use range-based for non-member begin and end function or sizeof operator since pt is not an array.
If you want to keep allocation of the two dimensional array,
new double [3][4]
there are two way to refer to this memory chunk,
1.,
double* pvalue = NULL;
pvalue = (double*)new double [3][4];
and 2.,
double (* parray)[4] = NULL;
parray = new double [3][4];
if you want to keep the pointer-to-pointer variable, i.e., double** ppvalue, then,
double** ppvalue = NULL;
ppvalue = new double*[3]; (a)
for(int i =0; i<3; i++)
ppvalue[i]=new double[4]; (b)
basically, you need to allocate memory for the array of pointers(a), and populate those pointers with concrete addresses.
The code you posted
double** pvalue = NULL; // Pointer initialized with null
pvalue = new double [3][4]; // Allocate memory for a 3x4 array
does not work because there is no way it can deduct the offset of pvalue, though it looks very nice and clear.
I also paste the full testing code so you can have a play:
#include <stdio.h>
int main() {
double* pvalue = NULL;
pvalue = (double*)new double [3][4];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
*(pvalue+i*4+j) = (double)i*(double)j;
printf("%f\n", *(pvalue+i*4+j));
}
}
double (* parray)[4] = NULL;
parray = new double [3][4];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
parray[i][j] = (double)i*(double)j;
printf("%f\n", parray[i][j]);
}
}
double** ppvalue = NULL;
ppvalue = new double*[3];
for(int i =0; i<3; i++)
ppvalue[i]=new double[4];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
ppvalue[i][j] = (double)i*(double)j;
printf("%f\n", ppvalue[i][j]);
}
}
}
As the compiler explicitly told you, new double [3][4] evaluates to a pointer of double (*)[4] type
double (*pvalue)[4] = new double [3][4];
You can't store that value in a double ** pointer.
P.S. The "tutorial" you linked is just nonsensical garbage.
I want to create an array with the values from 0 to 4000 by increments of 100 and add those to an array.
I don't have much of as to how to do it.
int wave[] = {};
for(int i = 0; i < 4000; i = i + 100){
//add to wave[] i
}
Any help would be appreciated
Since you can use C++, the default option for storing an array of integers is std::vector:
std::vector<int> wave;
for (int i = 0; i <= 4000; i += 100)
wave.push_back(i);
If you want to have a C array as the result (e.g. for compatibility with other code that uses such arrays), because you know the final size of your array in advance, you better mention the size in the array definition:
int wave[41];
int index = 0;
for (int value = 0; value <= 4000; value += 100)
wave[index++] = value;
If you didn't know the final size, and for some reason didn't want to use std::vector, you'd have to use dynamically-allocated arrays (with malloc or new[]).
int main()
{
int wave[4096/100 + 1];
for(int i = 0, j=0; i < 4096; i = i + 100, j++)
wave[j]= i;
}
I'm trying to create two dimensional array and assign objects into it. What's important is, that I want to do this using POINTERS. I want to achieve it like this:
Create pointer which will point to array of pointers.
Having array pointers I create next 10 cells in memory for example to store there individual object.
This is my code:
I create basic pointer for storing the address for array of pointers:
SpecialPoint **arrayOfPointsOnTheMap = NULL;
Next I initialize this array:
arrayOfPointsOnTheMap = new SpecialPoint*[size];
And then create cells in memory:
for (int i = 0; i < szer; i++) {
arrayOfPointsOnTheMap[i] = new SpecialPoint[wys];
}
And for the end I want to assign object to this newly created array:
SpecialPoint *pontInTable;
for (int i = 0; i < szer; i++) {
pontInTable = arrayOfPointsOnTheMap[i];
for (int j = 0; j < wys; j++) {
pontInTable[j] = new SpecialPoint();
}
}
But I get error when trying to create new object int array. I'm a little confused about it. Can anyone help?
What you want to do in the assignment part is not very clear so I will answer based on my best guess. Let`s say your class is as follows:
class SpecialPoint
{
public:
int x;
int y;
SpecialPoint(int xx, int yy)
{
x=xx;
y=yy;
}
SpecialPoint()
{
x=0;
y=0;
}
};
Then you can use the following code to create and initialize your 2d array:
int size = 4;
int wys = 3;
SpecialPoint** arrayOfPointsOnTheMap = new SpecialPoint*[size];
for(int i = 0; i < size; i++)
{
arrayOfPointsOnTheMap[i] = new SpecialPoint[wys];
} // you have your array at that point
SpecialPoint fakePoint(5,6); // create a special point
for(int i=0; i < size; i++)
{
for(int j=0; j < wys; j++)
{ // Assign your special point instance to all the array cells.
arrayOfPointsOnTheMap[i][j] = fakePoint;
}
}
After you are done with the array, do not forget to clean memory using:
for(int i = 0; i < size; i++) {
delete [] arrayOfPointsOnTheMap[i];
}
delete [] arrayOfPointsOnTheMap;
Good luck!
The following code allocates a 10 element array of pointers to doubles.
int i=0;
double* dp[10];
for (int i = 0; i < 10; ++i)
{
*(dp[i]) = 0.0;
}
for (int i = 0; i < 10; ++i)
{
cout<< *dp[i]<< endl;
}
Now how do I initialize each of these doubles to 0.0.
Write a loop that allocates space for each double and initializes it:
for (i = 0; i < 10; i++) {
dp[i] = new double;
*(dp[i]) = 0.0;
};
Are you sure you really need an array of pointers, not just an array of doubles? The latter would be simpler:
double dp[10] = {};
The empty initializer list defaults all the elements to 0.0.
Example with std::vector:
std::vector<double*> myArray(10);
std::fill(myArray.begin(), myArray.end(), new double(0.0));
(prefer classes from STL instead of C-style array in C++)
CASE1:
int nrows=5;
int ncols=10;
int **rowptr;
rowptr=new int*;
for(int rows=0;rows<nrows;rows++) {
for(int cols=0;cols<ncols;cols++) {
*rowptr=new int;
}
}
CASE2:
int nrows=5;
int ncols=10;
int **rowptr;
for(int rows=0;rows<nrows;rows++) {
rowptr=new int*;
for(int cols=0;cols<ncols;cols++) {
*rowptr=new int;
}
}
I am able to insert and print values using both ways. What is the difference in initializations?
What is the difference?
#1 just allocates memory enough to hold a integer pointer and not an array of integer pointers.
#2 Causes a memory leak by just overwritting the memory allocation of the previous iteration.
I am able to insert and print values using both the ways
Memory leaks and Undefined behaviors may not produce immediate observale erroneous results in your program but they sure are good cases of the Murphy's Law.
The correct way to do this is:
int nrows = 5;
int ncols = 10;
//Allocate enough memory for an array of integer pointers
int **rowptr = new int*[nrows];
//loop through the array and create the second dimension
for (int i = 0;i < nrows;i++)
rowptr[i] = new int[ncols];
You have a memory leak in both cases.
The proper way to initialize such a "2d" array is
int** arr = new int*[nrows];
for (int i = 0; i < nrows; i++)
arr[i] = new int[ncols];
Note however, that it isn't a 2d array as defined by C/C++. It may not, and probably will not, be consecutive in memory. Also, the assembly code for accessing members is different.
In your case, the accessing by indexing is equivalent to *(*(arr+i)+j)
And in the case of a 2d array it's *(arr + N_COLS*i + j) when N_COLS is a compile time constant.
If you want a true 2d array you should do something like this:
int (*arr)[N_COLS] = (int(*)[N_COLS])(new int[N_ROWS * N_COLS])
You'd better use 1d array to manage 2d array
int **x = new int*[nrows];
x[0] = new int[nrows*ncols];
for (int i = 1; i < nrows; i++)
x[i] = x[i-1] + ncols;
for (int i = 0; i < nrows; i++)
for (int j = 0; j < ncols; j++)
x[i][j] = 0;
delete [] x[0];
delete [] x;