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

Why does this code print the correct string?

Our professor wrote this code to demonstrate scanning and printing strings,

char flower[7][50];
int i, n;
for (i = 0; i < 7; i++)
{
    printf("Enter the name of the flower number %d : ", i + 1);
    scanf("%s", &flower[i][50]);
}
printf("\nEnter the number of the flower you want : ");
scanf("%d", &n);
printf("Flower number %d is %s\n", n, flower[n]);

I have been using C for almost 2 years now, and I feel like I grasped the fundamental concepts pretty well. But, for some reason, I just can’t understand this piece of code.

Why is scanf("%s", &flower[i][50]) used here instead of scanf("%s", flower[i]) or scanf("%s", &flower[i][0])? What does that 50 even mean?
Why is the index n used rather than n - 1 in printf("Name %d is %s\n", n, flower[n])?

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

I did ask her about it, but the answers she gave were not very comprehensive. She said that "because we used i+1 in the loop to print 1 instead of 0, we are going to use the same index to print the string needed, hence why we use flower[n]", which doesn’t answer anything.

Any help would be appreciated. Thanks in advance!

I entered the following strings followed by the index :

Rose
Lily
Tulip
Orchid
Carnation
Hyacinth
Chrysanthemum
6

Output :

Hyacinth

>Solution :

It seems as if your professor is probably thinking that arrays index from 1 (like they maybe do in some other languages), when they actually index from zero in C.

This is evidenced by this:

printf("Enter the name of the flower number %d : ", i + 1);

And then this:

scanf("%s", &flower[i][50]);

&flower[i][50] is the same as &flower[i + 1][0].

However, that is not a valid address on the final iteration of the loop, because the actual array indexes from [0] to [6]. This will invoke Undefined Behaviour.

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