2

I get this error with this code:

string folder;
getline(cin, folder);

string folder2 = folder + "/index.txt";
const char* oldhtml[] = { folder2.c_str() };
folder2 = folder + "/index.html";
const char* newhtml[] = { folder2.c_str()};
rename(oldhtml, newhtml);

The error occurs with: rename(oldhtml, newhtml);

I am fairly new to C++. So if this is a simple fix I apologise

nvoigt
  • 75,013
  • 26
  • 93
  • 142
Damon Jenkins
  • 352
  • 1
  • 3
  • 12

3 Answers3

13

It seems you don't understand this line:

const char* oldhtml[] = { folder2.c_str() };

That declares an array of length 1. The array element is a pointer which is initialized with the result of folder2.c_str() (probably, pointing to the internal storage of the string).

However you then change folder2 on the next line. This invalidates the result of any previous calls to c_str, so oldhtml[0] is now a dangling pointer.

A better way to write this code is to use string all the way:

string oldhtml = folder + "/index.txt";
string newhtml = folder + "/index.html";
rename(oldhtml.c_str(), newhtml.c_str());
M.M
  • 138,810
  • 21
  • 208
  • 365
1

const char* oldhtml[] creates an array of char* (similar to const char**), basically, an array of string (many char*), when you want a string (one and only one char*).

To create a regular pointer, use:

const char* oldhtml or const char oldhtml[].

jpo38
  • 20,821
  • 10
  • 70
  • 151
  • actually it creates a `const char * []`. Arrays and pointers are different. – M.M Jul 09 '15 at 12:38
  • @MattMcNabb, runtime arrays and pointers are completely interchangable (apart from `delete[]`) – WorldSEnder Jul 09 '15 at 12:42
  • @WorldSEnder no. [See here](http://stackoverflow.com/questions/1335786/c-differences-between-char-pointer-and-array) for some discussion, or read the C FAQ (or C++ FAQ). – M.M Jul 09 '15 at 12:43
  • @MattMcNabb, that question is for compile-time-static arrays, not runtime arrays – WorldSEnder Jul 09 '15 at 12:48
-1

Use const char* oldhtml = folder2.c_str() instead: there's no need to have an array of const char*

Be aware though that oldhtml will only be valid for as long as folder2 is in scope and remains unaltered. Which is doesn't. You modify it later. Boom!

By the way, if rename changes either input parameter, then the program behaviour will be undefined.

P45 Imminent
  • 8,319
  • 4
  • 35
  • 78
  • Presumably it is the Standard C++ function `std::rename(char const *old_filename, char const *new_filename);` – M.M Jul 09 '15 at 12:37