0

I am defining structure using separate unit which is first.c, and then looking to access it in my main module by using function call processSructFromMain. But only direct call to printf is worked. Call to processStructFromMain simply does not produce results at all. "Struct2 " in second printf does not show results as well.

What I am doing wrong ?

All of the in c, 11 standard

main:

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



void processStructFromMain(myStruct *s){
    printf("anotherProcess %s \n", s->name);
}

int main() {
    myStruct* s = getStructFromFirst();
    printf("Struct1 %s \n", s->name);



    processStructFromMain(s);
    printf("Struct2 %s \n", s->name);
    return 0;
}

first.c

#include "first.h"


myStruct *getStructFromFirst() {
    char* chr = "THIS IS STRING \0";
    myStruct* s = &(myStruct){.name=chr};
    return s;
}

first.h

#ifndef TESTONE_FIRST_H
#define TESTONE_FIRST_H

struct MYSTRUCT{
    char* name;
};


typedef struct MYSTRUCT myStruct;

myStruct* getStructFromFirst();


#endif //TESTONE_FIRST_H
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
mgs_bravo
  • 3
  • 5

1 Answers1

3

That temporary (myStruct){.name=chr}; does no longer exist once your getStructFromFirst() returns. You return the address of an Object that does no longer exist. Why use a pointer anyway?

myStruct getStructFromFirst(void)
{
    myStruct s{ .name = "foo" };
    return s;
}

// ...

int main(void)
{
    // ...
    myStruct foo = getStructFromFirst();
    processStructFromMain(&foo);
}

Also ...

char* chr = "THIS IS STRING \0";

there is no need to manually zero-terminate string literals. "THIS IS STRING" is zero terminated already.

Another thing: When a function in C does not take any parameters the parameter list in the prototype and its definition should be void: T foo(void);. A function with an empty parameter list like T foo(); takes an unspecified number of arguments.

Swordfish
  • 12,971
  • 3
  • 21
  • 43
  • thanks it explains. so by returning not a pointer but object from getStructFromFirst defined in first.c, should make this object alive in rest of the programm execution, right ? – mgs_bravo Jan 20 '19 at 13:39
  • @mgs_bravo Yes. The value is copied upon `return` just like an `int` would be copied. – Swordfish Jan 20 '19 at 13:54