Converting Strings using pointer to pointer

#include <stdio.h>

void cat_convert(char **);
int main() {
char dog[] = "Dog";
char **ptr;

*ptr = dog;
cat_convert(ptr);
printf("%s\n",dog);
return 0;
}

void cat_convert(char **str) {
*str = "Cat";
}

-My program is fairly straightforward, converting "Dog" to "cat" via a helper function, however I receive a Segmentation fault when I run it. I traced the error to the line " *ptr = dog ", however I don't know why that would give such an error. Help please?
You're dereferencing uninitialized pointer ('ptr' must point somewhere before you can do '*ptr').
If you think of ptr as the address of a pointer to the start of a string, then *ptr = dog is dereferencing an unitialised pointer. You're then overwriting the memory at that unknown location.

A better way to do what you've attempted is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>

void cat_convert(char **);

int main() {
  char dog[] = "Dog";
  char *ptr;

  ptr = dog;
  cat_convert(&ptr);
  printf("%s\n",dog);
  return 0;
}

void cat_convert(char **str) {
  *str = "Cat";
}
Topic archived. No new replies allowed.