Search code examples
cscopefunction-declarationfunction-parameter

How do I store the name of a input string for a different C file?


What I am trying to do is ask the name of someone and then storing it so I can use it for different scripts. Here is what I have so far.

main.c

#include <stdio.h>
#include "functions.h"
int main()
{
    printf("welcome to the dungeon crawler.\n");
    //ask for the name//
    printf("please state your name: ");
    char name[100];
    scanf("%s", name);
    printf("hello %s.\n", name);
    main2();
    return 0;
}

main2.c

#include <stdio.h>
#include "functions.h"
int main2()
{
    printf("%s\n", name);
    return 0;
}

functions.h

#ifndef FUNCTIONS_H_INCLUDED
#define FUNCTIONS_H_INCLUDED
int name;
#endif // FUNCTIONS_H_INCLUDED

When I try to run it, main2 says (null).


Solution

  • This declaration in main

    char name[100];
    

    declares a local variable that is not alive outside main.

    This declaration in functions.h

    int name;
    

    declares a global variable of the type int that is zero initialized.

    You have two choices.

    Either the function main2 will have a parameter of the type char * or const char *

    int main2( const char *name );
    

    (Place the function declaration in the header functions.h)

    and will be called like

    main2( name );
    

    Or remove the global variable

    int name;
    

    in the header functions.h and instead of it move the local declaration

    char name[100];
    

    from the module main.c in the header declaring it like

    extern char name[100];
    

    In one of the modules in the file scope you place the variable declaration for example like

    char name[100];
    

    On any case the declaration of the function main2 must be placed in functions.h.