0

Why do char array's in C not require a element specifier but integer array's do?

For example:

  #include <stdio.h>                                                              
                                                                                   
  int main(void){                                                                 
                                                                                                                                                             
  char array1[100];                                                               
  int array2[100] = {1,2,3,4};                                                    
                                                                                   
  fgets(array1, 100, stdin);                                                      
  printf("%s", array1);    // This prints the string inputted without a specifier                                                       
                                                                                  
  printf("%d ", array2);  // This throws an error since there is no specifier                                                     
                                                                                                                                                                                                                                                                                                                   
      return 0;
  }

1 Answers1

0

Arrays passed to functions decay to pointers. The %s format specifier expects a pointer to char, which is what you are passing, so all is well. Likewise in the next line you are passing a pointer to int, but %d expects an actual int, not a pointer. So it doesn't work.

The fundamental difference is that %d is meant to print a single integer, but %s is meant to print a whole array of characters (i.e. a string).

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82