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

What is the difference between &x, *x and x in C?

I’m starting to learn C and i noticed that sometimes we use

scanf("%d", &x[i]) 

and sometimes it’s left as simple:

scanf("%d", x[i])

Can someone please explain the difference to me? I don’t understand when we have to put & and when not to use it.
Also I don’t understand when we have to use *x? and what does it do?

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

>Solution :

The reason to use that & is to get a pointer. scanf always needs pointers, because it’s going to use it to give you a value back. But & is not the only way to get a pointer.

If you have a single int, char, long, float, or double variable, you will need to use a & to get a pointer of it to pass to scanf:

int i;
scanf("%d", &i);
char c;
scanf(" %c", &c);
long l;
scanf("%ld", &l);
float f;
scanf("%f", &f);
double d;
scanf("%lf", &d);

If you are reading a string, however, you usually do not need an &:

char str1[10];
scanf("%9s", str1);
char *str2 = malloc(20);
scanf("%19s", str2);

The reason you do not need a & in either of these cases is that you already have a pointer, although a full explanation of this fact will require more words than I suspect I’ll have time for in this answer.

This ends up being one of the reasons why scanf is a terribly problematic function. scanf is most useful during your first few weeks as a C programmer, when you have a lot of different things to learn, and scanf seems like an easy way to get user-entered values in to your program for it to work on. But you can’t really understand how to call scanf without understanding pointers, and pointers aren’t something you’re going to want to learn about until later.

So at first, a reasonable set of rules for successful scanf use is:

if your format is you should:
%d, %f, %lf use an &
%c use an &, and also use an extra space: " %c"
%s not use an &

See also this answer.

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