Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Struct variable doesn't work in main function in c

I’m trying to get a struct variable from another file in 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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?

>Solution :

The structure passed as a parameter to the function is only a copy. To modify the structure of the main function in the this_test function, you must pass its address. It’s like the scanf function where you have to pass the address of the variables you want to modify.

#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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading