简体   繁体   中英

Command Flow in C, function call after printf

So I have this super simple C code here taking a user input and prints it out followed by a "T-Plus" while loop. In this case I chose a random name for testing "whoa", but the while loop is not called. My question is, why does the "T-Plus: %d\n" while loop print not be called after the printf() function?:

#include <stdio.h>

char getString();
void tcount(void);


int main(void)
{
    tcount();
}

void tcount(void)
{
    // class scanf user input
    printf("%s", getString());

    int i = 1;
    do
    {
        printf("T-Plus: %d\n", i);
        i++;
    } while( i < 51 );
}

char getString()
{
    char name;
    printf("Please a string name: \n");
    scanf("%s", &name);
    return name;
}

Now when I run it, this becomes the output:

$ ./namecount
Please a string name:
whoa

but the T-Plus: string does not get called.

I see two issues here:

1) In function getString() you are trying to read/scan a string in a char, you need memory to store the string and a terminating char, so you can use either of these two ways

Use a char array eg char name[50]; or

Use a char pointer and allocate memory using malloc eg char *p_name = malloc(sizeof(char)*50);

2) You are then trying to return this string which is stored in local variable (which would get destroyed as soon as function ends) so you should use the second approach (use malloc) and return the pointer.

So your code would look like:

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

char * getString();
void tcount(void);


int main(void)
{
    tcount();
}

void tcount(void)
{
    // class scanf user input
    char *p_name = getString();
    printf("%s", p_name);
    free(p_name);

    int i = 1;
    do  
    {   
        printf("T-Plus: %d\n", i); 
        i++;
    } while( i < 51 );
}

char *getString()
{
    char *p_name = malloc(sizeof(char)*50);
    printf("Please a string name: \n");
    scanf("%s", p_name);
    return p_name;
}

Above answer did not work, Okay so I've edited the code like this, it compiles fine. But raises a segmentation fault though.

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

char * getString();
void tcount(void);

int main(void)
{
    tcount();
}

void tcount(void)
{
    // class scanf user input
    char *name = getString();
    printf("%s", name);
    free(name);

    int i = 1;
    do
    {
        printf("T-Plus: %d\n", i);
        i++;
    } while( i < 51 );
}


char * getString()
{
    char *p_name[50];
    printf("Please a string name: \n");
    scanf("%49s", (char *) &p_name);
    return *p_name;
}

When the program is run, it asks for your input but still raises a Segmentation fault (core dumped).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM