Reputation: 352
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
Upvotes: 2
Views: 7176
Reputation: 21514
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[]
.
Upvotes: 1
Reputation: 141534
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());
Upvotes: 13
Reputation: 8591
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.
Upvotes: -1