简体   繁体   English

结构变量在 c 中的主 function 中不起作用

[英]Struct variable doesn't work in main function in c

I'm trying to get a struct variable from another file in c.我正在尝试从 c 中的另一个文件中获取结构变量。 But when I do define a variable inside of other file and trying to printing this variable in main file it didn't work.但是当我在其他文件中定义一个变量并尝试在主文件中打印这个变量时它不起作用。

Main File主文件

#include <stdio.h>
#include <stdlib.h>
#include "tesst.h"

int main()
{
   struct tst t;
   this_test(t);
   printf("%s", t.string);

   return 0;
}

Other File Header其他文件 Header

#ifndef _TESST_H
#define _TESST_H

struct tst
{
   char *string;
};

void this_test(struct tst t);

#endif

Other File其他文件

#include <stdio.h>
#include <stdlib.h>
#include "tesst.h"

void this_test(struct tst t)
{
   t.string = "this is test";
}

When I tried to execute this program it print nothing.当我试图执行这个程序时,它什么也不打印。 How can I solve this problem?我怎么解决这个问题?

The structure passed as a parameter to the function is only a copy.作为参数传递给 function 的结构只是一个副本。 To modify the structure of the main function in the this_test function, you must pass its address.修改this_test function中的主要function的结构,必须通过它的地址。 It's like the scanf function where you have to pass the address of the variables you want to modify.就像 scanf function 一样,您必须在其中传递要修改的变量的地址。

#include <stdio.h>

struct tst
{
   char *string;
};

void this_test(struct tst *t)
{
   t->string = "this is test";
}

int main()
{
   struct tst t;

   this_test(&t);
   printf("%s", t.string);

   return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM