简体   繁体   中英

How to reverse an address of char pointer array

I'm trying to reverse an address of char pointer array, program is working but it doesn't show anything and stopping.

void swapArr(char ** arr, int n)
{
    int i;
    char ** temp;   
    for(i=0;i<n;i++)
    {
        *temp=arr[i];
        arr[i]=arr[n-i+1];
        arr[n-i+1]=*temp;
    }       
}

void main()
{
.
.
.
      cin>>lenArr;
      char *arr = new char[lenArr];
      swapArr(&arr,lenArr);
.
.
.
}

To swap the contents of an an address in a pointer, you need to swap the contents of the pointer (not what the pointer is pointing to). This could lead to undefined behavior because you are making the pointer point to some other location.

Note: the following is untested

char * my_pointer = "Hello";
char * temp_pointer = my_pointer;
cout << "before reversing the pointer: " << static_cast<void *>(temp_pointer) << "\n";
std::reverse(static_cast<uint8_t *>(&my_pointer),
             static_cast<uint8_t *>(&my_pointer) + sizeof(my_pointer));
cout << "after reversing the pointer: " << static_cast<void *>(my_pointer) << endl;

Edit 1: Reversing an array of pointers
Given:

  char * array_of_pointers[25];

You could use:

  std::reverse(&array_of_pointers[0], &array_of_pointers[25]);

You must allocate memory for temp . Do the following during declaration of temp -

char ** temp= new char *[(const int) n];   

However, it's better to use std::string in your case if you work in C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM