更改结构中元素的值
我是结构新手。我正在尝试编写一个具有结构的程序,该结构应该存储字符数组及其长度。我希望能够更改长度的值,因为我将创建诸如修剪/连接数组之类的函数。这是我编写的代码:
#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;
}
尽管调用了 strleng,
A.length
的值并没有改变。
(一)为什么?
(ii) 还有其他方法吗?
I'm new to structs. I am trying to write a program that has a struct, and the struct is supposed to store a character array and its length. I want to be able change the length's value as I would be creating functions like trimming/concatenating the array. Here is a code I wrote:
#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;
}
The value of A.length
is not changing inspite of calling strleng
.
(i)Why?
(ii) Is there another way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于初学者来说,函数调用中参数的求值顺序是未指定的。
因此,在此调用中,
参数表达式
A.length
的计算可以发生在调用函数strleng 之前,反之亦然。
其次,像这样声明的函数
strleng
处理在main中声明并用作参数的原始对象
A
的副本。因此更改副本不会影响原始对象。您需要通过指向该对象的指针通过引用传递该对象。
在 main 中,您应该编写例如,
请注意,一方面,数据成员
length
被声明为具有unsigned int
类型,另一方面,在您的原始文件中函数
strleng 您正在使用有符号类型
int
的对象,并且函数返回类型也是int
。该函数应至少使用相同的类型unsigned int
而不是类型int
。For starters the order of evaluation of arguments in a function call is unspecified.
So in this call
the evaluation of the argument expression
A.length
can occur before calling the functionstrleng
or vice versa.Secondly the function
strleng
declared likedeals with a copy of the original object
A
declared in main and used as an argument. So changing the copy does not influence on the original object.You need to pass the object by reference through a pointer to it.
and in main you should write for example
Pay attention to that on one hand, the data member
length
is declared as having the typeunsigned int
On the other hand, within your original function
strleng
you are using an object of the signed typeint
and the function return type is alsoint
. The function should use at least the same typeunsigned int
instead of the typeint
.尝试下面的代码:
您将得到输出:
6 6 1
。我现在应该得到答案了。希望能帮到你,c在线编译器:https://www.onlinegdb.com/online_c_compiler 。
Try the code below:
You will get output:
6 6 1
. I should get the answer now.I hope it can help you, c online compiler: https://www.onlinegdb.com/online_c_compiler.
更新的代码
Updated Code