tags:

views:

176

answers:

3

If i have char* str; how do I write a function that accepts str and can make changes to str so that, the changes persist after the function returns?

what I have is:

char *str = (char *) malloc(10);
sprintf(str, "%s", "123456789");
//str points to 1
move_ptr(&str);
//str points to 2

void move_ptr(char** str)
{
    *str++;
}

is there a better way to do that?

+9  A: 

Just access the data through the pointer, in the function:

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

void change_string(char *str)
{
  size_t i;

  /* As an example, make it all upper case. */
  for(i = 0; str[i]; ++i)
    str[i] = toupper(str[i]);
}

int main(void)
{
  char buffer[32];
  char *str = buffer;

  strcpy(str, "test string");
  change_string(str);
  printf("it's now %s\n", str);

  return EXIT_SUCCESS;
}

Come to think of it, you'll notice that the standard strcpy() function is exactly of the category you describe. It's a very common operation in C.

UPDATED: The question has been significantly rewritten, now it seems to be more about changing the pointer itself, rather than the data. Perhaps this was the meaning all along, but I didn't understand.

The solution in the question is fine, but personally I find it more convenient to work with return values, if possible:

char * change_pointer(char *str)
{
  return str + 1;
}

int main(void)
{
  char *str = "test string";

  printf("now '%s'\n", str);
  str = change_pointer(str);
  printf("now '%s'\n", str);
  return EXIT_SUCCESS;
}

The pointer(s) could of course also be const-declared, and should be if no changes to the buffered text are needed.

unwind
@unknown: That sounds like a different question ... But of course that's one way of solving it. If possible, I prefer to use the return value, so that the function returns the updated string pointer.
unwind
+1  A: 
pmg
A: 

Your example may be over simplified, but just in case... Be careful of doing things like this because you're going to leak memory. After your function call, you no longer have a pointer to (part of) the original memory you allocated.

As mentioned by unwind, returning the new pointer may be a better choice. While it achieves the same goal, it makes it more obvious that you need to keep the original pointer around for the purposes of releasing the memory. The counter argument being that it gives the impression that you can free the original pointer once you have the return value, which you can't do because they both point at (different locations) in the same memory block.

RHSeeger
It's worse than just a leak, calls to **free()** with _any value not returned by_ **malloc()** will almost certainly cause a crash.
NVRAM