使用依赖结构中值的函数更新结构值
Update a struct value using a function that relies upon values in the struct
typedef struct example_Type{
int x;
int y;
int z;
} exampleType;
void foo(exampleType* exampleStruct){
exampleStruct->z = "value from exampleStruct, variable x" + "value from exampleStruct, variable y";
}
int main(){
exampleType struct1;
struct1.x = 10;
struct2.y = 5;
foo(&struct1);
}
我该怎么办?
exampleStruct->z = exampleStruct.y + exampleStruct.x;
这行得通吗?我想调用在 x 和 y 中找到的值,但我该怎么做?
使用
exampleStruct->z = exampleStruct->y + exampleStruct->x;
而不是
exampleStruct->z = exampleStruct.y + exampleStruct.x;
->
运算符取消引用其左操作数,然后访问一个
引用对象的成员。所以,上面的语句和doing
是一样的
(*exampleStruct).z = (*exampleStruct).y + (*exampleStruct).x;
是的,你可以这样做:
exampleStruct->z = exampleStruct->y+exampleStruct->x;
注意:您使用的是指针,因此在访问元素时将使用 ->
而不是 .
。
type_name x;
创建类型为 type_name
的变量
type_name *y;
创建一个指向 type_name
类型变量的 指针 。
在使用 struct
时,您需要像这样使用指针:
struct smth *test;
test->a=0;
strncpy(test->word,"hello",5);
当您使用普通结构(无指针)时,您会:
struct smth test;
test.a=0;
strncpy(test.word,"hello",5);
问题陈述
exampleStruct->z = "value from exampleStruct, variable x" + "value from exampleStruct, variable y";
可以重写为
"value from exampleStruct, variable z" = "value from exampleStruct, variable x" + "value from exampleStruct, variable y";
如果您认为可以在 foo()
中使用 exampleStruct->z
,那么为什么不使用 exampleStruct->x
和 exampleStruct->y
?它们是同一结构变量的成员。它肯定会起作用。试试写
exampleStruct->z = exampleStruct->x + exampleStruct->y;
你可以的,
exampleStruct->z = exampleStruct->x + exampleStruct->y;
您正在获取作为指针的结构。
typedef struct example_Type{
int x;
int y;
int z;
} exampleType;
void foo(exampleType* exampleStruct){
exampleStruct->z = "value from exampleStruct, variable x" + "value from exampleStruct, variable y";
}
int main(){
exampleType struct1;
struct1.x = 10;
struct2.y = 5;
foo(&struct1);
}
我该怎么办?
exampleStruct->z = exampleStruct.y + exampleStruct.x;
这行得通吗?我想调用在 x 和 y 中找到的值,但我该怎么做?
使用
exampleStruct->z = exampleStruct->y + exampleStruct->x;
而不是
exampleStruct->z = exampleStruct.y + exampleStruct.x;
->
运算符取消引用其左操作数,然后访问一个
引用对象的成员。所以,上面的语句和doing
(*exampleStruct).z = (*exampleStruct).y + (*exampleStruct).x;
是的,你可以这样做:
exampleStruct->z = exampleStruct->y+exampleStruct->x;
注意:您使用的是指针,因此在访问元素时将使用 ->
而不是 .
。
type_name x;
创建类型为 type_name
type_name *y;
创建一个指向 type_name
类型变量的 指针 。
在使用 struct
时,您需要像这样使用指针:
struct smth *test;
test->a=0;
strncpy(test->word,"hello",5);
当您使用普通结构(无指针)时,您会:
struct smth test;
test.a=0;
strncpy(test.word,"hello",5);
问题陈述
exampleStruct->z = "value from exampleStruct, variable x" + "value from exampleStruct, variable y";
可以重写为
"value from exampleStruct, variable z" = "value from exampleStruct, variable x" + "value from exampleStruct, variable y";
如果您认为可以在 foo()
中使用 exampleStruct->z
,那么为什么不使用 exampleStruct->x
和 exampleStruct->y
?它们是同一结构变量的成员。它肯定会起作用。试试写
exampleStruct->z = exampleStruct->x + exampleStruct->y;
你可以的,
exampleStruct->z = exampleStruct->x + exampleStruct->y;
您正在获取作为指针的结构。