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

标签 c printing struct typedef

我想创建一个打印方法来打印出 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/

相关文章:

c - Ora*C PCC-S-02201,在期望以下 : 之一时遇到符号 "L"

c - 如何在 C 中不使用零填充截断 FAT32 文件系统中的文件?

c - 为什么指针到指针转换的隐式指针是合法的?

c# - Winforms RichTextBox 中的两列

sql - sql触发打印消息

C 在链表开头插入元素

c++ - 检查 vector 中的所有结构是否相等

c++ - 变量作为全局范围内的结构 - 如何定义?

c - 函数调用是否与 %rax 以外的其他寄存器混淆?

printing - (漂亮)在 Common Lisp 中打印大对象