I was trying to add a string to end of a pointer to pointer array, or insert a string in a selected position, then delete a selected element, using 3 function.
The first function I used to add a string to the end of a pointer to pointer:
char **add(char **pp, int size, char *str)
{
if (size == 0)
{
pp = new char *[size+1];
}
else
{
char **temp = new char *[size+1];
for (int i = 0; i < size; i++)
{
temp[i] = pp[i];
}
delete[]pp;
pp = temp;
}
pp[size] = new char[strlen(str) + 1];
strcpy(pp[size], str);
return pp;
}
The second function I used to insert a string in a selected position:
char **InsPtr(char **pp, int size, int ncell, char *str)
{
char**temp = new char *[size+1]; //добавить новый элемент [size+1]
for (int i = 0, j = 0; j < size + 1; j++)
{
if (j != ncell)
{
temp[j] = pp[i];
i++;
}
else
{
temp[j]=new char[ strlen(str)+1];
strcpy(temp[j], str);
}
}
delete[] pp;
pp = temp;
return pp;
}
And here is the function I used to delete any string I choose:
char **DelPtr(char **pp, int size, int ncell)
{
char**temp = new char*[size-1];
for (int i = 0, j = 0; i < size; i++)
{
if (i != ncell)
{
temp[j] = pp[i];
j++;
}
}
delete[]pp[ncell];
pp[ncell] = 0;
delete[] pp;
pp = temp;
return pp;
}
I used **add(char **pp, int size, char *str) to add 4 strings to the array, then insert a string in a selected position by **InsPtr(char **pp, int size, int ncell, char *str), or delete a string by **DelPtr(char **pp, int size, int ncell), and it works correctly without any error.
But when I use **InsPtr(char **pp, int size, int ncell, char *str), then after this function I use **DelPtr(char **pp, int size, int ncell)
I got an error at runtime.
Here is main function:
void main()
{
int size = 0;
char **pp = 0;
pp = add(pp, size, "1111");
size++;
pp = add(pp, size, "2222");
size++;
pp = add(pp, size, "3333");
size++;
pp = add(pp, size, "4444");
size++;
int insert=2,DelS= 2;
for (int i = 0; i < size; i++)
{
cout << *(pp + i) << endl;
}
pp = InsPtr(pp, size, insert, "natasha");
cout << endl;
for (int i = 0; i < size + 1; i++)
{
cout << *(pp + i) << endl;
}
pp = DelPtr(pp, size, DelS);
cout << endl;
for (int i = 0; i < size ; i++)
{
cout << *(pp + i) << endl;
}
system("pause");
}
Here is the result i got before the error at runtime:
1111
2222
3333
4444
Insert in the second index "natasha":
1111
2222
natasha
3333
4444
Delete the second index "natasha":
1111
2222
3333
std::string?