Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using Scanf with pointers

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading