【发布时间】:2015-06-04 15:52:21
【问题描述】:
我试图了解在通过引用传递参数时何时需要使用地址运算符&(对于介意我不精确的读者,请将其阅读为模拟传递引用 ) 到函数而不修改函数本身。我将使用structs 给出两个小例子。在两者中struct 都是通过引用传递的,但其中一个涉及& 的使用,而另一个则不涉及。在这种特殊情况下的解释可能会涉及到第二个示例中malloc() 的使用,我可以猜到,但我想要一个更有经验的意见。此外,我的问题更笼统:当我可以通过引用而不使用& 时,是否有规则(或至少是经验法则)?
#include <stdio.h>
#include <stdlib.h>
struct Author {
char *Name;
int Born;
int Died;
char *Notable_Works;
};
void print_struct(struct Author *thomas_mann);
int main()
{
struct Author thomas_mann;
thomas_mann.Name = "Thomas Mann";
thomas_mann.Born = 1875;
thomas_mann.Died = 1955;
thomas_mann.Notable_Works = "Der Zauberberg";
print_struct(&thomas_mann);
return EXIT_SUCCESS;
}
void print_struct(struct Author *thomas_mann)
{
printf("%s was born in %d and died in %d.\n",
thomas_mann->Name, thomas_mann->Born, thomas_mann->Died);
printf("His most notable work includes ‘%s’.\n",
thomas_mann->Notable_Works);
}
示例 2
#include <stdio.h>
#include <stdlib.h>
struct Author {
char *Name;
int Born;
int Died;
char *Notable_Works;
};
void print_struct(struct Author *thomas_mann);
int main()
{
struct Author *thomas_mann = malloc(sizeof(struct Author));
if (!thomas_mann) {
fprintf(stderr, "memory allocation failed");
exit(EXIT_FAILURE);
}
thomas_mann->Name = "Thomas Mann";
thomas_mann->Born = 1875;
thomas_mann->Died = 1955;
thomas_mann->Notable_Works = "Der Zauberberg";
print_struct(thomas_mann);
free(thomas_mann);
return EXIT_SUCCESS;
}
void print_struct(struct Author *thomas_mann)
{
printf("%s was born in %d and died in %d.\n",
thomas_mann->Name, thomas_mann->Born, thomas_mann->Died);
printf("His most notable work includes ‘%s’.\n",
thomas_mann->Notable_Works);
}
【问题讨论】:
-
您没有“选择”是否通过
x或&x(也没有重击规则)。它取决于函数所期望的 type。在您的两个示例中,这是传递参数的 only 正确方法(无需修改函数或更改调用者中的类型)。