我很好奇为什么不能在作为参数传递到函数时修改结构的变量。我知道参数是按值传递的,但是当传递结构变量时,您将其引用作为值传递。
当然C不会在堆栈上创建结构的副本,因为传入的结构引用的值与将结构指针传入函数的值相同。
#include <stdio.h>
#include <stdlib.h>
typedef struct String {
char* name;
int x;
} String;
/* Func Protos */
void foo(String str);
void bar(String * str);
void banjo(String str);
int main() {
String str = *(String *)malloc(sizeof(String));
str.x = 5; /* x == 5 */
foo(str); /* x == 5 still */
printf("%d\n", str.x);
banjo(str); /* x == 5 still */
printf("%d\n", str.x);
bar(&str); /* and of course, x = 0 now */
printf("%d\n", str.x);
}
void foo(String str) {
printf("%d\n", str); /* Same value as if we passed String * str */
str.x = 0;
}
void bar(String * str) {
printf("%d\n", *str);
str->x = 0;
}
void banjo(String str) {
printf("%d\n", str);
String * strptr = &str; /* This should be identical to passing String * str */
strptr->x = 0;
}
生成此输出:
3415000
5
3415000
5
3415000
0
任何帮助都将不胜感激!
最佳答案
void banjo(String str) {
printf("%d\n", str);
String * strptr = &str; /* This should be identical to passing String * str */
strptr->x = 0;
}
C是传递值。在带有
banjo
参数的str
函数中得到的是main
str
对象的副本。所以你的
banjo
函数等于:void banjo(String str) {
printf("%d\n", str);
strptr.x = 0; // useless, the object is discarded after function returns
}
顺便说一下,
printf("%d\n", str);
是无效的。d
转换说明符需要一个int
,但您正在传递一个结构值。调用调用未定义的行为。如果要打印str
对象的地址,请使用:printf("%p\n", (void *p) &str);