-1

How the conditional part of for loop work in this program.Please anyone explain this to me.phone[i][0][0] means first list first string and first letter.

#include<stdio.h>
#include<string.h>

char phone[][2][40] = {

    "Fred","555-1010",
    "Barney","555-1234",
    "Ralph","555-2347",
    "Tom","555-8396",
    "",""
};


int main(void)
{
    char name[80];
    int i;

    printf("Name? ");
    gets(name);

    for(i=0; phone[i][0][0]; i++)
        if(!strcmp(name, phone[i][0]))
        printf("Number: %s", phone[i][1]);

    return 0;
}
Kawsar_Ahmed
  • 55
  • 1
  • 9
  • Just pick it apart: What is `phone`? What is `phone[i]`? What is `phone[i][0]`? What is `phone[i][0][0]`? Draw it all up on paper, it might help. – Some programmer dude Dec 11 '16 at 07:54
  • 4
    On an unrelated note: Don't use `gets`. Never ever use `gets`. It is dangerous, it has been obsolete since the C99 standard, and in the latest C11 standard been removed completely. – Some programmer dude Dec 11 '16 at 07:56
  • [This answer](http://stackoverflow.com/a/4346650/1033027) elaborates on @Someprogrammerdude's comment. – Jules Dec 11 '16 at 08:23

1 Answers1

1

A null character evaluates to a false in your exit condition, and that is what your doing in phone[i][0][0]. And your for loop will terminate when i=4 or when you reach the fifth entry in the array.

As side note never use gets. User fgets instead as pointed out in comment,

fgets(name,40,stdin); // 40 max chars including null character.
sjsam
  • 21,411
  • 5
  • 55
  • 102