what is the difference between these two programs

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jinnejeevansai
    New Member
    • Nov 2014
    • 48

    what is the difference between these two programs

    #include <stdio.h>

    int main(void) {
    int i;
    char a[3];
    for(i=0;i<3;i++ )
    scanf("%d",a[i]);
    printf("%d",ato i(a));
    return 0;
    }
    this is giving the output as 0 but if i take input as a[3]={'1','2,'3'} it is giving correct what is difference in usage of atoi
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Have you tried %c in the scanf since you have a char array? The %d is for int.

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      The "%d" argument tells scanf to store an integer value, but you tell it to store that integer value in a char. An integer is too big to fit in a char so scanf ends up writing past the end of array a. Something weird is going to happen.

      The second argument to scanf is the address where the integer is to be stored. Your second argument is a[i]. That isn't an address. Something weird is going to happen.

      The argument to atoi is a null-terminated string. Array a does not contain a string, and it isn't null-terminated. If array a doesn't happen to contain a null character (0), then atoi will read past the end of the array. Something weird is going to happen.

      What do you want this program to do?

      Comment

      Working...