1

I need to pass a char pointer to function, then change the value that it points to inside the function and print values outside the function.

The problem I have is that I'm losing it when I leave function and try to print it outside. What can I do to avoid this?

This is an code example:

    char array[] = "Bada boom";
    char *pText = array;
    reverseText(pText);
    cout << (pText);

cout should print

moob adaB

When I print inside the function, everything is fine(it prints reversed). My task is to print It out outside the function (as you can see in a 4th line of code)

This is the full of code which have the bug (printing inside func works, outside didn't work)

#include <iostream>
#include <string>
#include <string.h>

using namespace std;

char reverseText(char *text);

int main(){

    char array[] = "Bada boom"; 
    char *pTekst = array;


    reverseText(pTekst);
    cout << (pTekst);                 //in here it doesn't work

}

char reverseText(char *text){
    char befRev[100]; int lenght=-1;

    /*until *text doesn't meet '\0' */
    for(int i=0;*text!='\0';i++){
        befRev[i]=(*text);
        text++;
        lenght++;
    }
    /*reversing*/
    int j=0;
    for(int i=lenght;i>=0;i--){
        *(text+j)=befRev[i];
        j++;
    }

    for(int i=0;i<=lenght;i++)               //in here it does print the right value
        cout << text[i]; 
};
12
  • 1
    how do you implement reverseText(). Commented Sep 8, 2014 at 18:04
  • "I know that inside the function i work on a copy of pointer that I sent as argument - can I return copy of that pointer?" Depends. If the copy is allocated dynamically (new/malloc) then yes, but make sure to delete/free it later. Commented Sep 8, 2014 at 18:06
  • Also, unless there's a great reason not to, use std::string instead of char* and almost all your problems will go away. :-) Commented Sep 8, 2014 at 18:08
  • Do I have to allocate both pointers? Pointer and its copy? Commented Sep 8, 2014 at 18:12
  • 2
    First understand the difference between changing the pointer, and changing the thing it points to. Then ask the person who gave you this task which one you should do. Commented Sep 8, 2014 at 18:38

5 Answers 5

4

Just re-arrange the array in-place. The pointer itself doesn't need to change:

#include <cstring>
#include <algorithm>

void reverseText(char* array)
{
  auto len = std::strlen(array);
  std::reverse(array, array+len);
}

int main()
{
  char array[] = "Bada boom";
  char *pText = array;
  reverseText(pText);
  std::cout << pText << std::endl;
}

Output:

moob adaB

If you really wanted to provide a pointer that points to a different address to the caller, you could simply return it:

char* foo(char* stuff)
{
  char* tmp = ....;
  ...
  // do some stuff
  ...
  return tmp;
}

Alternatively, you could pass the pointer by reference, but the intent is less clear than in the previous version:

void foo(char*& stuff)
{
  stuff = something_else;
}

But in both cases, you must make absolutely sure the thing the new pointer points to is valid outside of the function. This might require some dynamic memory allocation. For your case, it seems the best and simplest option is to re-arrange the array in place.

Sign up to request clarification or add additional context in comments.

6 Comments

Imma a begginer, and I want to write my own functions. std::reverse is not what I want to use, i'll do it with my own loops and arrays to better understand cpp
@Jacob That is just an example. The point is that you can modify the array in place.
char* foo will work fine I think... If I return a copy, I should set the original pointer adress of copy?
By the way, can someone tell me if my question was clear to You guys? Is it usefull? I couldn't find the info searching trough the internet.
You should make sure whatever you return points to a valid address. You really should sort in-place.
|
1

To answer your question, you have an error in logic. Notice that in your first loop in reverseText you increment the local pointer text. In your second loop you did not reset text to it's original value so beforeRev is being copied over starting at location text+offset.

If you were to look at pText on return from call to reverseText you would find it contains: "Bada boom\0moob adaB"

Your reverseText should be renamed palindrome :)

1 Comment

This doesn't answer the question. To critique or request clarification, please do so under the OPs question. If you do not have enough rep, you can always comment under your own post.
0

This is pretty straightforward. Some points to note:

  1. An array decays to a pointer when you pass it to a function.
  2. You are passing in a null terminated string. So the length of the char array you are passing in is the length of the string (including white space) +1.
  3. Because you are using a pointer there is no need to assign a temp variable to hold everything.

Here is some code in C that is easy to translate to C++. Working out the actual reverse algorithm is left for you as an exercise.

#include<stdio.h>

void reverseText(char* text)
{
    // Hint: It can be done in one loop!

    int i;

    for(i = 0; i < 9; i++)
    {
        // Your algorithm to reverse the text. I'm not doing it for you! ;)
        *(text + i) = 'r';

    }

}

int main()
{
    char array[] = "Bada boom";
    reverseText(array);
    printf("The text reversed: %s\n", array);

    return 0;
}

3 Comments

Sorry, my bad. It is just an alternative notation.
i prefer *(text+i) notation ! :) If i change argument it in the function, will it change outside? (i mean in your code)
Yes, it will behave exactly the same because the array is decaying to a pointer when passed to the function, so any changes you make to the data pointed to will be reflected outside the function.
0

My final code:

#include <iostream>

void reverseText(char* text){   
    int length=-1; char tmp;
    /*Length = sign from 0 to 8 without counting explicit NUL terminator*/
    for(int i=0;*(text+i)!='\0';i++){   
        length++; 
    }
    int j=0; int i=length;
    while(j<i){
        tmp=*(text+j);          //tmp=first
        *(text+j)=*(text+i);    //first=last
        *(text+i)=tmp;          //last=tmp
        j++;
        i--;
    }
}

int main(){
    char array[] = "Bada boom"; 
    char *pText = array;
    reverseText(pText);
    std::cout << pText;
}

I should have read more about pointers before I started this exercise.

Comments

-1

You can either return a pointer or pass a pointer to pointer as a function argument.

//pointer to pointer
void reverseText(char** textPtr) {

    char* newText = ...; //initialize;
    ...
    *textPtr = newText;  //assign newText
}

//return pointer
char* reverseText(char* text) {

    char* newText = ...; //initialize

    return newText;
}

Remember that if you allocate memory in this function you must do it dynamically (with new or malloc) and you have to free it afterwards (with delete or free respectively). Memory allocation in a function like this is probably a bad practice and should be avoided.

9 Comments

These are valid approaches, although this is C++ so a smart pointer would be better.
I'd love to know what's wrong with my answer. Anyone?
No need to do this. OP is passing a pointer to an array, the array can be modified in place.
@juanchopanza the question is about changing a pointer, not a memory it points to.
@AdamKosiorek I suspect that OP wants to change the array because they have needlessly made a local copy of it. It isn't clear that making a copy is a requirement. It doesn't look like it is.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.