-2

I have same problems with the below code.I try to read from file a destination.

void airplane::readFlight(void)
{
    char temp[100];
    ifstream f("date.txt");
    if(!f)
        {
            cerr<<"Err";
            //exit(EXIT_FAILUARE);
        }
    f>>nrFlight;
    for (int i=0;i<nrFlight;i++)
        {
            f.getline(temp,99);
            destination[i]=new char(strlen(temp)+1);
            strcpy(destination[i],temp);
        }
    f.close();
}

And i get this errors:

  1. invalid conversion from ‘char’ to ‘char*’
  2. initializing argument 1 of ‘char* strcpy(char*, const char*)’
  3. Invalid arguments 'Candidates are:char * strcpy(char *, const char *)

This error appears when i allocate memory and when i try to copy the information. Thx.

Barmar
  • 741,623
  • 53
  • 500
  • 612

2 Answers2

1

Possibility 1

If you want to have a dynamic array destination with n elements of strings (instead of unformated char arrays) you should declare it first:

string* destination = new string [n];

and then you can use it:

char temp[100];
[...]
f.getline(temp,99);
destination[i] = temp;

don't forget to release memory:

delete[] destination;
destination = NULL;

Possibility 2

If you want to use char arrays,then destination must be an array of char arrays (-> 2-dimensional). Declaration:

char** destination = new char* [n];

Usage:

char temp[100];
[...]
f.getline(temp,99);
destination[i] = new char [strlen(temp)+1];
strcpy(destination[i],temp);

Release memory:

for(i=0 ; i<n ; i++)
{
   delete[] destination[i];
   destination[i] = NULL;
}
delete[] destination;
destination = NULL;
Skydef
  • 61
  • 7
0

It should be:

destination[i] = new char[strlen(temp)+1];

See What's the difference between new char[10] and new char(10)

I suspect you also have a problem with the declaration of destination. If you add that to the question, I'll add the correction here.

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612