0

What are the uses of a pointer to a pointer in C and when to use? Because I'm used to see something like this most often const char *foo(char **foo); but when I do something like this:

#include <stdio.h>
char *foo(char **foo)
{
printf("b : %s \n ", foo);
*foo = "World";
printf(" c %s \n ", foo);
}

main()
{
static char *test = "Hello";
foo(&test);
printf("a : %s \n ", test);
} 

it compiles good but both b and c get corrupted and a never changes. please help me , what am I doing wrong?

VMai
  • 10,156
  • 9
  • 25
  • 34
  • 1
    change to `printf("b : %s \n ", *foo);` ... `printf(" c %s \n ", *foo);` and `return *foo;` – BLUEPIXY Jul 12 '14 at 08:37
  • If that "compiles good", then you are using the wrong compiler, the wrong settings or ignoring the warnings the compiler is giving you. gcc gave me three warnings: –  Jul 12 '14 at 08:58
  • warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char **' [-Wformat=] printf("b : %s\n", foo) ; warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char **' [-Wformat=] printf("c : %s\n", foo) ; warning: no return statement in function returning non-void [-Wreturn-type] –  Jul 12 '14 at 09:06
  • Try compiling with -Wall option. – pankaj Jul 12 '14 at 11:01
  • Thanks i did, thats my problem i guess. I also understand that pointer to a pointer can be used to modify the pointer, so this is okay now! #include char *foo(char **foo) { printf("b : %s \n ", *foo); *foo = "World"; printf(" c %s \n ", *foo); return *foo; } int main() { static char *test = "Hello"; foo(&test); printf("a : %s \n ", test); } – Abdullahi Usman Jul 12 '14 at 12:20

1 Answers1

0

A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value.

http://www.tutorialspoint.com/cprogramming/c_pointer_to_pointer.htm

Sujith Gunawardhane
  • 1,251
  • 1
  • 10
  • 24