Why use double pointer? or Why use pointers to poi

2018-12-31 16:04发布

When should a double pointer be used in C? Can anyone explain with a example?

What I know is that a double pointer is a pointer to a pointer. Why would I need a pointer to a pointer?

标签: c pointers
19条回答
何处买醉
2楼-- · 2018-12-31 16:55

As said one of the application of double poinnter is to update the string so that changes made are reflected back.

#include <iostream>
#include <cstring>  // for using strcpy
using namespace std;

void change(char **temp)
{
   strcpy(temp[0],"new");
   strcpy(temp[1],"value");
}

int main()
{
   char **str;
   str = (char **)malloc(sizeof(char *)*3);
   str[0]=(char *)malloc(10);
   str[1]=(char *)malloc(10);
   strcpy(str[0],"old");
   strcpy(str[1],"name");
   char **temp = str;  // always use the temporary variable
   while(*temp!=NULL)
{
    cout<<*temp<<endl;
    temp++;
}
temp = str;   // making it point it to the original head because we have changed the address in while loop above
change(str);
while(*temp!=NULL)
{
   cout<<*temp<<endl;
   temp++;
}

free(temp);
free(str[0]);
free(str[1]);
free(str);
查看更多
登录 后发表回答