Home > OS >  Using Scanf with pointers
Using Scanf with pointers

Time:10-08

I am fairly new to C and I am having trouble using scanf with pointers. I have been told to get user inputs for 3 int and 1 char values and then print them back out using pointers.

This is the best I could come up with so far:

int a, b, c;
char d;
int *x = &a;
int *y = &b;
int *z = &c;
char *e = &d;

scanf("Enter 3 Ints and 1 Char:%d %d %d %c", x, y, z, e);
printf("The numbers are:\n");
printf("%d\n %d\n %d\n %c\n", a, b, c, d);

return 0;

When I enter the values the following is printed out:

2 3 4 c
The numbers are:
32708
 -613084440
 32708
 �

Again, I'm very new to programming so I apologize if this is a stupid mistake or something obvious that I have missed.

CodePudding user response:

You are not checking the return value of your scanf, otherwise you would know that it returns 0, as in 'no elements read'.

Your scanf expects you to write exactly what you are putting in there, so, if you entered Enter 3 Ints and 1 Char:2 3 4 c, it would probably work.

What you want, however, is this:

printf("Enter 3 Ints and 1 Char: ");

if (scanf("%d %d %d %c", &a, &b, &c, &d) != 4)
    printf("Invalid input detected\n");
else
    printf("The numbers are:\n%d\n %d\n %d\n %c\n", a, b, c, d);

The first line will print the prompt to the console, the second will read the values into variables.

There is no need to create separate pointer variables for this purpose.

  • Related