how do you declare an array of dynamic string.
i mean..if you have
char name[501][41];
how do u declare the above in dynamic mode using *.
char *name[41]?
or
char *name*?
thanks in advance;
how do you declare an array of dynamic string.
i mean..if you have
char name[501][41];
how do u declare the above in dynamic mode using *.
char *name[41]?
or
char *name*?
thanks in advance;
You have several options. Here's one:
char ** strings;
strings = new char* [501]; //display an array of 501 char pointers.
for(int i = 0; i < 501; ++i)
strings[i] = new char[41]; //each of the 501 char pointers will have the address of the first char in an array of 41 char.
Hi,
There is a tiny bit of a trick to doing this. Basically, you need to get enough memory for the characters AND enough memory for a pointers to it.
This assumes that both the 501 and 41 in your example are effectively variables that are only known at run time.
So
int m(501); // obviously this can be set elsewhere
int n(41);
...
char *tmpC=new char[m*n];
char **OutPtr=new char*[m];
for (int i=0;i<m;i++)
OutPtr[i]=tmpC + (i*n);
Now just use OutPtr. (or return it from a function).
Obviously, I had better give the delete method.
it is just
delete [] *OutPtr;
delete [] OutPtr;
Hope that helps.
typedef char Name[41];
Name* name = new Name[501];
...
delete [] name;
This is also 2 dimensional, pointers of pointers
float **grades;
int *examNo, studentNo, i, j;
cout << "No of students: ";
cin >> studentNo;
grades = new float *[studentNo];
examNo = new int [studentNo];
for (i = 0; i < studentNo; i++){
cout << "No of exams for " << i;
cin >> examNo[i];
grades[i] = new float[examNo[i]];
for (j = 0; j < examNo[i]; j++)
grades[i][j] = 0;
}
for (i = 0; i < studentNo; i++)
delete [] grades[i];
delete [] grades;
delete [] examNo;
This is array of pointers
const int size = 6;
int *triangle[size], i, j;
for (i = 0; i < size; i++){
triangle[i] = new int[i+1];
for (j = 0; j < i+1; j++)
triangle[i][j] = i+1;
}
for (i = 0; i < size; i++){
for (j = 0; j < i+1; j++)
cout << triangle[i][j];
cout << endl;
}
for (i = 0; i < size; i++)
delete [] triangle[i];
And pointers of array
double (*points)[2];
int i, j, pointNo;
cout << "Number of points: ";
cin >> pointNo;
points = new (double[pointNo])[2];
for (i = 0; i < pointNo; i++){
cout << "Enter x coordinate: ";
cin >> points[i][0];
cout << "Enter y coordinate: ";
cin >> points[i][1];
}
for (i = 0; i < pointNo; i++){
cout << "x: " << points[i][0];
cout << ", y: " << points[i][1] << endl;
}
delete []points;
char** chpp = (char**) malloc(sizeof(char));
char* chp = "aaa";
chpp[0] = chp;
chp = "bbb";
chpp[1] = chp;
chp = "ccc";
chpp[2] = chp;
for(int i=0; i<3; i++)
cout << chpp << endl;
I've tried to write it simple. However you can expand it and use it in a loop.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.