Hola, practicando un poco con punteros me surgió un problema. Estoy creando una clase llamada TStringList (como la que existe en Delphi) y creé una función Add(). Funciona bastante bien, el problema ocurre cuando introduces más de 5 o 6 cadenas, que la primera cadena se pierde y salen caracteres raros.
Código main.
#include <iostream>
#include "stringlist.h"
using namespace std;
const int CHAR_MAX_LENGTH = 20;
int showmenu()
{
int option = 0;
do
{
cout << "1.- Añadir string" << endl;
cout << "2.- Mostrar strings" << endl;
cout << "3.- Salir" << endl;
cout << "Introduce una opcion: ";
cin >> option;
}while(option < 1 && option > 3);
return option;
}
int main()
{
char buff[CHAR_MAX_LENGTH];
int option = 0;
TStringList *List = new TStringList();
do
{
option = showmenu();
switch(option)
{
case 1: cout << "Introduce una cadena: ";
cout.flush();
cin >> buff;
List->Add(buff);
break;
case 2: for (int i = 0; i < List->GetCount(); i++)
cout << "Item " << i + 1 << ": " << List->GetItem(i) << endl;
break;
}
}while(option != 3);
delete(List);
return 0;
}
Código stringlist.h
#ifndef _H_STRINGLIST
#define _H_STRINGLIST
struct SL_ITEM{
char *string;
};
class TStringList{
private:
SL_ITEM *Items;
long numItems;
public:
TStringList();
~TStringList();
void Add(char *cadena);
long GetCount();
char * GetItem(long Index);
};
#endif
Código stringlist.cpp
#include "stringlist.h"
#include <memory>
#include <malloc.h>
#include <string.h>
TStringList::TStringList()
{
numItems = 0;
}
TStringList::~TStringList()
{
if (numItems > 0)
{
for (int i = 0; i < numItems; i++)
Items[i].string = NULL;
Items = NULL;
/*
Aquí también tengo alguna duda.
Probé con delete [] Items; pero compilado en Linux me suelta un stack error, en Windows, simplemente se cierra la aplicación :huh:
*/
}
}
void TStringList::Add(char *cadena)
{
if (numItems > 0){
SL_ITEM * NewItems = (SL_ITEM*) malloc((numItems + 1) * sizeof(SL_ITEM));
/*for (int i = 0; i < numItems; i++)
{
NewItems[i].string = (char *) malloc(strlen(Items[i].string) + 1);
strcpy(NewItems[i].string, Items[i].string);
}*/
memcpy(NewItems, Items, sizeof(*Items));
memcpy(Items, NewItems, sizeof(*NewItems));
NewItems = NULL; //Creo que no hace falta
}
else Items = (SL_ITEM*) malloc(sizeof(SL_ITEM));
Items[numItems].string = (char *) malloc(strlen(cadena) + 1);
strcpy(Items[numItems].string, cadena);
numItems++;
}
long TStringList::GetCount()
{
return numItems;
}
char * TStringList::GetItem(long Index)
{
if (Index < numItems && Index >= 0)
return Items[Index].string;
else return NULL;
}
Espero que puedan echarle un ojo y comentar.
Saludos.