user11303607
user11303607

Reputation:

Not getting output

I was trying to scan a string input from the user and then print it in the next line, but I'm not able to figure out, as I'm new to coding, why it is showing no output! Below is the code-

main()
{
    char* w1,w2,w3,e1,e2,e3;
    printf("List of Words");
    printf("\tMeanings");
    scanf("%s",&w1);
    printf("\n%s",w1);
    getch();
}

I expected w1 to print under "List of Words" but it isn't showing any output.

Upvotes: 0

Views: 51

Answers (1)

Achal
Achal

Reputation: 11931

Here

char* w1; /* uninitialized pointer */
scanf("%s",&w1); /* for w1 no memory is allocated. Also & is not required since w1 tends to points to some address */

w is character pointer and pointer needs to point to some valid memory location, but in your case w1 not having any valid memory.

Allocate memory for w first and then put the input data into w using scanf(). For e.g

#define BUF_MAX_LENGTH 10

char *w1 = malloc(BUF_MAX_LENGTH);
if(w1 == NULL) {
  /* @TODO error handling */
}

And then scan the data into w1. For e.g

scanf("%s", w1);

And once usage is done with w do not forget to free the dynamically allocated memory to avoid memory leakage. For e.g

free(w1);

Side note, do avoid declaring character variable & character pointer variable in same declaration to improve code readability. For e.g

char* w1,w2,w3,e1,e2,e3; /* mixed up */

can be

char* w1 = NULL; /* All pointer declaration */
char w2,w3,e1,e2,e3; /* All normal char variable */

Upvotes: 2

Related Questions