我以以下示例为例,以查看直接传递对象与传递指针之间的区别:
#include "stdio.h"
// Car object
typedef struct Car {
char* name;
unsigned int price;
} Car;
void print_car(Car car) {
printf("<Car: %s, Price: $%d>", car.name, car.price);
};
void print_car2(Car *car) {
printf("<Car: %s, Price: $%d>", car->name, car->price);
};
int main(int argc, char* argv[]) {
Car chevy = {chevy.name = "Chevy", chevy.price = 45000};
print_car(chevy);
Car mazda = {chevy.name = "Mazda", chevy.price = 30000};
print_car2(&mazda);
return 1;
}
除了第一种方法对我而言更具可读性和易于理解之外,两者之间有什么区别?什么时候传递指针是唯一的选择,为什么在上述情况下两者都起作用?
通常(不仅对于结构体)将变量传递给函数会复制该变量,因此,如果您要更改此变量,则必须返回更改后的副本的值,但您可能希望更改变量并返回还有其他事情,在这种情况下,您别无选择,将指针作为参数exemple传递:
第一个例子是传递变量
int useless_func(int nb) /*nb is actually a copy of the variable passed as argument */
{
nb++; /* the copy was incremented, not the real variable */
return nb; /* the new value is returned */
}
int main()
{
int nb = 1;
useless_func(nb); /* here nb is still = 1 cause it wasn't altered by the functionalists */
nb = useless_func(nb); /* here nb is = 2 cause it took the return value of the func */
}
现在是指针的第二个愚蠢的例子:
char *useless_func(int *nb) /* nb is now a pointer to the variable */
{
*nb++; /* the derefencement of the pointer (so the variable value) was incremented */
return strdup("This is a useless return"); /* we return some other stupid stuff */
}
int main()
{
int nb = 1;
char *str = useless_func(&nb); /* now nb is = 2 and str is an allocated useless string woohoo */
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句