duck
duck

Reputation: 141

C: using function to get input in different format

I am an extreme newbie in C, I wrote following code:

# include <stdio.h>

static char * getInfo(char info[15]){
    static char res[15];
    printf("Please enter your %s:\n", info);
    scanf("%s", res);
    return res;
}

static int getNum(char info[15]){
    static int res;
    printf("Please enter your %s:\n", info);
    scanf("%d", &res);
    return res;
}

int main(){
    static char * name;
    static char * title;
    name = getInfo("name");
    title = getInfo("title");
    
    int age;
    age = getNum("age");
    
    printf("Welcome %s %s age %d\n", name, title, age);
    return 0;
}

/*
Please enter your name:
Ben
Please enter your title:
Hansan
Please enter your age:
32
Welcome Hansan Hansan age 32
Program ended with exit code: 0
*/

I am trying to get input of string and integer format using functions.

I don't understand why Hansan is duplicated, I will be so glad if someone offers some suggestions.

Upvotes: 1

Views: 77

Answers (1)

kiran Biradar
kiran Biradar

Reputation: 12732

It is because you are using static variable to store the input, static variable always holds the latest data stored in it.

static char * getInfo(char info[15]){
    static char res[15];
    printf("Please enter your %s:\n", info);
    scanf("%s", res);
    return res;
}

change it to

char * getInfo(char info[15]){
    char *res = malloc(15);
    printf("Please enter your %s:\n", info);
    scanf("%s", res);
    return res;
}

and free the memory once done processing in main.

  int main(){
    char * name;
    char * title;
    name = getInfo("name");
    title = getInfo("title");
    
    int age;
    age = getNum("age");
    
    printf("Welcome %s %s age %d\n", name, title, age);

    free(name);
    free(title);
    return 0;
}

Upvotes: 2

Related Questions