Moaaz Siddiqui
Moaaz Siddiqui

Reputation: 29

Error in passing the address of a pointer holding array elements to a function in c++

I created an array of characters and then assigned them to a pointer. Then I passed that pointer address to a function which would reverse the array character by character and print them out. I can not understand the error in my code.

// ConsoleApplication1.cpp : This file contains the 'main' function. 
// Program execution begins and ends there.

#include <iostream>
#include<conio.h>
using namespace std;
void reverses(char* p) {
    int count = 17;
    for (int i = 0; i < 18; i++) {

        cout << *(p + i);
        char temp = *(p + i);
        *(p + i) = *(p + count);
        *(p + count) = temp;
        count--;
        cout << *(p + i);           
    }
}
int main() {
    char names[18] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 
                       'j','k','l','m','n','o','p','q','r' };
    char* ptr = &names[0];

    for (int i = 0; i < 18; i++) {
        reverses(ptr + i);
    }
}

Upvotes: 1

Views: 86

Answers (1)

anastaciu
anastaciu

Reputation: 23802

You call the reverse function 18 times in a loop, and each time you pass a pointer to the next character of the char array, so after the second loop you are already accessing elements out of the bounds of the array.

Call reverses only once, and print the characters after the reversion is complete.

void reverses(char* p) {
    int count = 17;
    for (int i = 0; i < 18 / 2; i++) {
        char temp = *(p + i);
        *(p + i) = *(p + count);
        *(p + count) = temp;
        count--;  
    }
}

int main()
{
    char names[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
                      'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r'};
    char *ptr = &names[0];
    reverses(ptr);

    for(int i = 0; i < 18; i++){
        std::cout << ptr[i];
    }  
}

Note that for a trivial reverse routine, only half of the cycles are needed otherwise you are returning the array to it's original form.


Here is a simplified, and thus more readable version where you pass the size of the array as an argument:

void reverses(char *p, int size)
{
    for (int i = 0; i < size / 2; i++, size--) // size would be 18
    {
        char temp = p[i]; // swap routine
        p[i] = p[size - 1];
        p[size - 1] = temp;      
    }
}

Using [] array notation is simpler and more readable, but if you prefer you can use the pointer notation:

void reverses(char *p, int size)
{
    for (int i = 0; i < size / 2; i++, size--)
    {
        char temp = *(p + i);
        *(p + i) = *(p + size - 1);
        *(p + size - 1) = temp;      
    }
}

The same end result, but less readable code.


I would use algorithm library std::reverse:

#include <algorithm>

//...

std::reverse(ptr, ptr + 17);

for(int i = 0; i < 18; i++){
    std::cout << ptr[i];
}

Upvotes: 1

Related Questions