Home > Back-end >  c char array returns some strange value
c char array returns some strange value

Time:10-18

After inserting values in dynamic char array, trying to get first value from the top. Method gives me back ² value. Can you help me with understanding, what I am doing wrong? Here is main method:

    char* arr = new char[5]();
    arr[0] = 'h';
    arr[1] = 'e';
    arr[2] = 'l';
    arr[3] = 'l';
    char result = topValue(arr, 5);
    cout << result;

Here is topValue() method:

char topValue(char* stackArr, int stackSize)
{
    for (int i = stackSize; i >= 0; i--)
    {
        std::cout << "In top: " << stackArr[i] << std::endl;
        if (stackArr[i] != '\0')
        {
            return stackArr[i];
        }
    }
} 

CodePudding user response:

In the first iteration of the loop, you access the array outside of its bounds, and the behaviour of the program is undefined.

Note that your function doesn't handle the potential case where all elements are the null terminator character. In such case the function would end without returning a value and the behaviour of the program would be undefined. Either handle that case, or carefully document the pre-condition of the function.

Furthermore, the program leaks memory. I recommend avoiding the use of bare owning pointers.

After inserting values in dynamic char array ...

You aren't inserting values into an array. It isn't possible to insert values into an array. The number of elements in an array is constant.

  • Related