// Program which inputs a string from user, reverses it and displays it.
#include <iostream>
usingnamespace std;
void string_reverse (char [], constint);
int main()
{
constint arraysize = 10;
char string[arraysize];
cout << "Please enter a string : ";
for (int i = 0; i < arraysize; i++)
{
cin >> string[i];
}
cout << "Reverse string is : ";
string_reverse (string, arraysize);
for (i = 0; i < arraysize; i++)
{
cout << string[i];
}
cout << endl;
return 0;
}
void string_reverse (char string[], constint arraysize)
{
int p = 0;
char temp[arraysize];
for (int i = (arraysize-1); i >= 0; i--)
{
temp[p] = string[i];
p++;
}
for (i = 0; i < arraysize; i++)
{
string[i] = temp[i];
}
}
In the string_reverse function, I have declared temp character type array but on line 38, the
I have declared a constant integer arraysize in line 35.
Now I have no clue why is this happening because I think as I have declared it as a constant integer variable, this should not happen. :/
You are passing the size of the array through to your function in the argument list. Then you are creating an array on the stack i.e. at runtime. The compiler needs to know the size of the array at the time of compiling, so that it will allocate the right amount of space for your variables in your function. To create an array on the stack you must use an integral value, if you want to create the array at runtime you must declare it on the heap:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
void string_reverse (char string[], constint arraysize)
{
int p = 0;
char* temp = newchar[arraysize];
for (int i = (arraysize-1); i >= 0; i--)
{
temp[p] = string[i];
p++;
}
for (int i = 0; i < arraysize; i++)
{
string[i] = temp[i];
}
delete[] temp;
}
It's a difference between just being const and being a true compile-time constant. The array size need to be a compile-time constant (except if dynamically allocated). arraysize inside the string_reverse is not a compile-time constant because it can be different depending on what value you pass to the function.
Thank you so much ajh32. Yes, this is exactly what I was looking for. My problem is solved but it would be great if you tell me two things.
1 - Why can't it be done what I was doing before?
2 - delete[] temp; What does this do and is it required here?
Because the compiler needs to know the size of your variables at compile time so that sufficient spaces is allocated on the stack for them all at runtime.
2 - delete[] temp; What does this do and is it required here?
You are taking space from the OS for your variable, and must tell the OS that you have finished with it and return it for use elsewhere. Failing to use the
delete
function for every use of
new
results in a memory leak. As a C++ programmer you are responsible for the correct freeing of memory you have used on the heap.