In pratica mi risulta che a e s non puntino alla stessa cella di ram, quindi anche se l'array puntato da s viene espanso, le successive operazioni su a risultano sballate...
Per risolvere ho modificato la funzione in modo che ritorni un puntatore a void (si potrebbe anche templatizzare la funzione), che rappresenta un puntatore al primo indice dell'array, che viene poi castato e assegnato ad a...
per farti capire meglio ti mostro gli output con i relativi codici:
codice:
//codice che produce errori
#include <iostream>
using namespace std;
typedef struct _mytype{
int a;
int b;
_mytype()
{
a = 3;
b = 6;
}
void stampa()
{
cout << a << ";" << b << endl;
return;
}
void mod(int x, int y)
{
a = x;
b = y;
return;
}
} myType;
void realloca(myType *s, const int x, myType &obj);
int main()
{
myType *a = new myType[10];
a[4].mod(2,7);
for(int k = 0; k < 10; k++)
{
a[k].stampa();
}
cout << "Riallocazione..." << endl;
myType obj1;
realloca(a,10,obj1);
for(int k = 0; k < 11; k++)
{
a[k].stampa();
}
system("pause");
return 0;
}
void realloca(myType *s, const int x, myType &obj)
{
myType * tmp = new myType[x];
for(int i = 0; i < x; i++)
{
tmp[i] = s[i];
}
delete[] s;
s = new myType[x+1];
for (int i = 0; i < x; i++)
{
s[i] = tmp[i];
}
s[x+1] = obj;
return ;
}
output:

codice:
//codice che sembra funzionare correttamente
#include <iostream>
using namespace std;
typedef struct _mytype{
int a;
int b;
_mytype()
{
a = 3;
b = 6;
}
void stampa()
{
cout << a << ";" << b << endl;
return;
}
void mod(int x, int y)
{
a = x;
b = y;
return;
}
} myType;
void* realloca(myType *s, const int x, myType &obj);
int main()
{
myType *a = new myType[10];
a[4].mod(2,7);
for(int k = 0; k < 10; k++)
{
a[k].stampa();
}
cout << "Riallocazione..." << endl;
myType obj1;
a = (myType*)realloca(a,10,obj1);
for(int k = 0; k < 11; k++)
{
a[k].stampa();
}
system("pause");
return 0;
}
void* realloca(myType *s, const int x, myType &obj)
{
myType * tmp = new myType[x];
for(int i = 0; i < x; i++)
{
tmp[i] = s[i];
}
delete[] s;
s = new myType[x+1];
for (int i = 0; i < x; i++)
{
s[i] = tmp[i];
}
s[x+1] = obj;
return s;
}
output: