gpt4 book ai didi

无法打印可能在 C 中使用 typedef 构造的 MyType 中的值

转载 作者:太空宇宙 更新时间:2023-11-04 04:54:48 25 4
gpt4 key购买 nike

我想创建一个打印方法来打印出 MyType 中的 int 和 string 值。但是它只适用于 doIt1。如何修改打印方法,有人可以帮忙吗?

#include<stdio.h>
#include<string.h>
typedef struct {
int i;
char s[1024];
} MyType;

doIt1(MyType *mt, int ii, char *ss){
mt->i=ii;
strcpy(mt->s, ss);
}

doIt2(MyType mt, int ii, char *ss){
mt.i=ii;
strcpy(mt.s, ss);
}

void print(MyType mt){
print("%d\n", mt.i);
print("%s\n", mt.s);
}

int main(int argc, char ** argv){
MyType mt1, mt2;
doIt1(&mt1, 12, "Other Stuff");
doIt2(mt2, 7, "Something");
print(mt1); // print out mt1
print(mt2); // print out mt2
}

最佳答案

doit2 中,您正在传递 mt 按值,也就是说,您正在复制。

doit2 函数中,mt 不是 mt2 的别名:它是另一个在 时将被丢弃的变量doit2 退出。

简单的说,当你打电话的时候

doIt2(mt2, 7, "Something");

您的代码将执行如下操作(简化):

{
MyType mt2_tmp = mt2;
/* execute doIt2 passing the copy, mt2_tmp, to the function */
doIt2(mt2_tmp, 7, "Something");
/* the function exits and the copy is thrown away */
}

关于无法打印可能在 C 中使用 typedef 构造的 MyType 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10214305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com