lundi 29 juin 2015

I dont understand how this array of pointers is working


I dont understand why I have to increment de variable contador before I do this

palabras[contador]=auxiliar; 

palabras is an array of char pointers that I declared like this:

char *palabras[13]; 

Which I think is the proper way to do it. This array of pointers would store words that have a max size of 12. I created contador as a global variable and initialized to 0. But if I don't put contador++; before using palabras[contador]=auxiliar the program will crash, for some reason I can't write in the palabras[0] array.

void leerArchivo()
{
     ifstream archivo("palabras.txt", ios::in);
     char linea[13];
     char *auxiliar;
     if(archivo.fail())
     {
          cerr<<"Error al abrir el archivo palabras.txt"<<endl;
          getch();
     }else
     {
           while(!archivo.eof())
           {
                 archivo.getline(linea, sizeof(linea));
                 contador++;  //???
                 auxiliar=linea;   //copy the first address of the array linea
                 palabras[contador]=auxiliar; 
                 cout<<" "<<palabraSize(palabras[contador])<<" ";  //????
                 cout<<palabras[contador]<<endl;
           }
           archivo.close();
     }
}


Aucun commentaire:

Enregistrer un commentaire