Home > Software design >  Struct variable doesn't work in main function in c
Struct variable doesn't work in main function in c

Time:09-17

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

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

CodePudding user response:

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;
}
  • Related