指针,结构,传递参数,递归

时间:2015-04-10 10:36:02

标签: c pointers recursion struct argument-passing

我有这样的代码:

typedef struct _Statistics {

  Some code here

} Statistics;

void function1(char *string, Statistics *statistic){

   Some code here

   function1(string1, statistic);
}
int main(){

   Statistics statistic;
   function1(string, &statistic);
}

这可能是一个愚蠢的问题,但我并不完全理解指针: 我明白为什么我用&在主要功能,&发送变量统计的地址,以便在function1中我可以修改它。但为什么我不使用&在递归函数1?

3 个答案:

答案 0 :(得分:4)

因为&statistic(在function1()中)是指针的内存地址,而不是指针包含的地址。

&statistic中的Statistics**类型为function1()


关于指针的几句话

我们假设我们定义了以下变量:

char c = 'a';
char *p_c = &c;

现在,我们将打印p_cc的值和内存地址:

printf("%c\n", c); // will print 'a'
printf("%c\n", *p_c); // will print 'a' 

printf("%p\n", &c); // will print the memory address of c
printf("%p\n", p_c); // will print the memory address of c

printf("%p\n", &p_c); // will print the memory address of p_c

最后我们定义一个char**,一个指向char的指针:

char **p_pc = &p_c;

printf("%c\n", **p_pc); // will print 'a'
printf("%p\n", *p_c); // will print the memory address of c
printf("%p\n", p_c); // will print the memory address of p_c

答案 1 :(得分:1)

有时以这种方式编写它会有所帮助:

void function1(char* string, Statistics* statistic){

变量statistic是指向Statistics的指针,而不是Statistics本身。如果您在function1中执行此操作:

   function1(string1, &statistic);

你会传递一个指向(因为&)指针(由于声明中的*)统计信息,这是不正确的。

您在main中声明statistic作为统计数据会增加混淆:您在两个范围内使用不同类型的相同变量名称。

使用不同的变量名称,它更清晰:

typedef struct _Statistics {
  Some code here
} Statistics;

void function1(char* string, Statistics* ptrstat){
   Some code here
   function1(string1, ptrstat);
}

int main(){
   Statistics statistic;
   function1(string, &statistic);
}

答案 2 :(得分:0)

一般情况下(即大多数语言),您可以通过值传递或通过引用传递。这取决于功能的定义及其“标志”;即声明它及其论据的方式。

传递值就像一个赋值,如果复制一个更大的结构,它将需要更长的时间。此外,该函数只接收一个副本,因此您可以更改函数中的参数,但这只会影响函数的本地副本(参数),并且不会更改原始值(在调用者中)传给你了。

相比之下,传递引用只是传递原始值的指针(存储器中的地址)。这要快得多(4或8个字节),但它确实意味着该函数不仅可以读取,还可以调用者的值。有时你想要这个!有时你没有。

在您的主体中,您拥有统计数据的价值。您调用的函数需要地址(*),因此您需要传递其地址(& statistic),而不是传递值(统计信息)。

在函数中,调用自身,你有一个指向统计信息(Statistics *)的指针,你必须传递一个指向统计信息的指针(统计*):因此,只需传递它,指针'统计'。