1

I'm trying to write a void function that gets a pointer to a pointer of a string (char**) as a parameter, and changes the original char* so it pointed to another string, lets say "hello".

Below is the code I've written:

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

void change_ptr(char **str_ptr)
{
    char hello[] = "hello";
    char *hello_ptr = hello;
    *str_ptr = hello_ptr;
}



int main()
{
    char str[] = "yay";
    char *str_ptr = str;
    char **ptr_to_str_ptr = &str_ptr;
    change_ptr(ptr_to_str_ptr);
    printf("%s\n", str);

    return 0;
}

As you can see, Im getting the pointer to the pointer of the char* "yay", delivering it to the function, and in the function I'm getting the pointer to "hello", and changes *str_ptr (which is the pointer to the original string) to the pointer to hello. But when I print str at the end, it prints "yay".

What am I doing wrong?

(when I debug with printing the addresses, everything seems fine.)

5
  • 1
    You need to print str_ptr. Note, however, that hello only exists within change_ptr(). Commented Oct 23, 2022 at 18:38
  • str is an array. str_ptr no longer points to it (after the call to change_ptr, it contains the value of an address which is no longer valid), but str still contains the contents "yay". Commented Oct 23, 2022 at 18:44
  • oh I get it. So I defined "yay" as char* str = "yay" instead, and now it worked. Thanks! Commented Oct 23, 2022 at 18:46
  • The char hello[] = "hello"; needs to be static char hello[] = "hello"; Commented Oct 23, 2022 at 18:47
  • You're accidentally printing out str, which you never changed, instead of str_ptr which you attempted to change. Commented Oct 23, 2022 at 18:56

1 Answer 1

1

This works:

#include <stdio.h>

void change_ptr(const char ** str_ptr)
{
  *str_ptr = "hello";
}

int main()
{
  char str[] = "yay";
  const char * str_ptr = str;
  const char ** ptr_to_str_ptr = &str_ptr;
  change_ptr(ptr_to_str_ptr);
  printf("%s\n", str_ptr);
}

Note that the string "hello" in this example is read-only because it is a string literal. I added const in a few places so you are reminded of this and the compiler will warn you if you try to write to the string. The pointer str_ptr can be modified, but not the string itself.

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

Comments

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.