I am new to cpp and have a question regarding arrays. The code I have below should create a reversed version of str and have it be stored in newStr. However, newStr always comes up empty. Can someone explain to me why this is happening even though I am assigning a value from str into it?
void reverse (char* str) {
char* newStr = (char*)malloc(sizeof(str));
for (int i=0;i<sizeof(str)/sizeof(char);i++) {
int index = sizeof(str)/sizeof(char)-1-i;
newStr [i] = str [index];
}
}
PS: I know that it is much more efficient to reverse an array by moving the pointer or by using the std::reverse function but I am interested in why the above code does not work.
sizeof(char*)isn't the size of the array. You should also usestd::string, or, if you have no choice, at leastnew/new[]anddelete/delete[]overmallocandfree.unique_ptrunique_ptrto fix that situation.unique_ptrto fix that, you need a better design and a good working knowledge of memory management. Don't throw abstractions at people before they understand what they're abstracting away.