-2

I have a function char enterComponent() and I would like to have it ask the user for a string name, and then return the name to where it was called.

This is the code I have

char enterComponent(){
    char name[8];
    printf("    enter next component name:  ");
    sscanf("%s", &name);
    return name;      
}

and this is what the debugger tells me

warning: format not a string literal and no format arguments [-Wformat-security]
warning: return makes integer from pointer without a cast [enabled by default]
warning: function returns address of local variable [-Wreturn-local-addr]

I was wondering if someone can tell me what I did wrong here.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294

3 Answers3

1

Do not return a pointer to an object with automatic storage duration and use scanf to read a string from stdin.

Basically change your function to:

void enterComponent(char *name)
{
    printf("    enter next component name:  ");
    scanf("%s", name);
}

That you could call this way:

 char name[256]; // reserve enough space, use fgets / sscanf for safety

 enterComponent(name);

 printf("%s\n", name);  // prints your string
ouah
  • 142,963
  • 15
  • 272
  • 331
0

Your function is defined as returning a single character. It should return a char *. However, you must not return your local variable name, since it is allocated on the stack, and will be overwritten once the function calling enterComponent() makes another call. Either you pass a buffer to the function, for the entered value to be returned in, or malloc memory for the return value (and don't forget to free it later!)

Thomas Stets
  • 3,015
  • 4
  • 17
  • 29
0

You should correctly declare the function that it would return a pointer to a dynamically allocated character array. For examoke

char * enterComponent()
{
    const size_t N = 8;
    char *name = malloc( N * sizeof( char ) );

    printf("    enter next component name:  ");

    if ( name ) fgets( name, N, stdin );

    return name;      
}

Of course you could allocate more than 8 characters, For example you could define N as for example 50.

Do not forget to free the returned pointer when it wiil not be needed any more.

free( name );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Thank you for the help. I'm looking it over and wondering why it prints out `" enter next component name: "` `" enter next component name: "` twice when the function is called the first time. But then after that, it only prints once. – johnnyboyyy Oct 23 '14 at 07:04
  • @johnnyboyyy It seems because you print this message twice: before the function call and inside the function body. – Vlad from Moscow Oct 23 '14 at 07:11