将其视为*(*display)
. 当您想将整数的地址传递给函数以便设置整数时,您可以使用:
void setTo7 (int *x) {
*x = 7;
}
: : :
int a = 4;
setTo7 (&a);
// a is now 7.
它与您所拥有的没有什么不同,只是您要设置指针的值,因此您需要将指针传递给该指针。很简单,不是吗?
试试这个:
#include <stdio.h>
#include <string.h>
static void setTo7 (int *x) { *x = 7; }
void appendToStr (char **str, char *app) {
// Allocate enough space for bigger string and NUL.
char *newstr = malloc (strlen(*str) + strlen (app) + 1);
// Only copy/append if malloc worked.
if (newstr != 0) {
strcpy (newstr, *str);
strcat (newstr, app);
}
// Free old string.
free (*str);
// Set string to new string with the magic of double pointers.
*str = newstr;
}
int main (void) {
int i = 2;
char *s = malloc(6); strcpy (s, "Hello");
setTo7 (&i); appendToStr (&s, ", world");
printf ("%d [%s]\n",i,s);
return 0;
}
输出是:
7 [Hello, world]
这将安全地将一个字符串值附加到另一个,分配足够的空间。双指针通常用于智能内存分配函数,在 C++ 中较少使用,因为您有一个原生字符串类型,但它对于其他指针仍然有用。