提问人:lazearoundallday 提问时间:3/13/2022 最后编辑:Vlad from Moscowlazearoundallday 更新时间:3/13/2022 访问量:820
更改结构中元素的值
Changing the value of an element in a struct
问:
我是结构新手。我正在尝试编写一个具有结构体的程序,并且该结构体应该存储一个字符数组及其长度。我希望能够更改长度的值,因为我将创建修剪/连接数组等函数。这是我写的代码:
#include <stdio.h>
#include <stdlib.h>
struct strstruct{
unsigned int length;
char string[20];
};
typedef struct strstruct stru;
int strleng(stru A){
int i=0;
while(A.string[i]!='\0'){
i++;
}
A.length =i;
return i;
}
int main(){
stru A = {1,
{'a','b','c','d','e','f'}
};
printf("%d %d\n",strleng(A),A.length);
return 0;
}
尽管调用了 ,但 的值不会改变。
(i)为什么?
(二)有没有其他方法可以做到这一点?A.length
strleng
答:
2赞
Vlad from Moscow
3/13/2022
#1
对于初学者来说,函数调用中参数的计算顺序是未指定的。
所以在这个电话中
printf("%d %d\n",strleng(A),A.length);
参数表达式的计算可以在调用函数之前进行,反之亦然。A.length
strleng
其次,函数声明如下strleng
int strleng(stru A);
处理在 main 中声明并用作参数的原始对象的副本。因此,更改副本不会影响原始对象。A
您需要通过指向对象的指针通过引用传递对象。
unsigned int strleng( stru *A){
unsigned int i=0;
while(A->string[i]!='\0'){
i++;
}
A->length =i;
return i;
}
在主要情况下,你应该写例如
unsigned int n = strleng( &A );
printf("%u %u\n", n, A.length );
注意,一方面,数据成员被声明为具有length
unsigned int
unsigned int length;
另一方面,在原始函数中,您使用的是有符号类型的对象,函数返回类型也是 。该函数应至少使用相同的类型,而不是 类型 。strleng
int
int
unsigned int
int
1赞
zhhui
3/13/2022
#2
试试下面的代码:
#include <stdio.h>
#include <stdlib.h>
struct strstruct{
unsigned int length;
char string[20];
};
typedef struct strstruct stru;
int strleng(stru* A){
int i=0;
while(A->string[i]!='\0'){
i++;
}
A->length =i;
return i;
}
int main(){
stru A = {1,
{'a','b','c','d','e','f'}
};
printf("%d %d %d\n",A.length, strleng(&A),A.length);
printf("%d \n",A.length);
return 0;
}
您将获得输出:。我现在应该得到答案。6 6 1
首先,如果要在函数中修改结构的值,则需要使用指针作为参数。
对于您的问题:
- 对于大多数 c 编译器来说,printf 函数内部的函数是从右到左排列的。我认为你的例子中的编译器就是这个。
- 对于某些 c 编译器,它会从左到右在一行中处理函数。
希望能帮到你,c在线编译器:https://www.onlinegdb.com/online_c_compiler。
1赞
Peal Mazumder
3/13/2022
#3
printf("%d %d\n",strleng(A),A.length);
- 首先,在这里您将参数传递给 strleng 函数,因为值意味着 strleng 函数的参数是 A 的副本。换言之,主函数中的变量 A 和 strleng 函数中的结构变量是两个自变量。因此,在 strleng 函数中更改 A.length 对 main 函数中的变量 A 不可见。(有许多关于按值传递与按引用传递的优秀在线资源。您可以检查这些以更好地理解)
- 大多数编译器从右到左获取 printf() 的每个参数。所以这里 A.length 首先执行,然后是 strleng(A)。因此,即使您通过引用传递参数,它仍将输出 6 1。
更新的代码
#include <stdio.h>
#include <stdlib.h>
struct strstruct {
unsigned int length;
char string[20];
};
typedef struct strstruct stru;
int strleng(stru* A) {
int i = 0;
while(A->string[i] != '\0'){
i++;
}
A->length = i;
return i;
}
int main() {
stru A = {1, {'a','b','c','d','e','f'}};
printf("%d %d %d\n", A.length, strleng(&A), A.length);//6 6 1
return 0;
}
评论