Search code examples
cfunctionprintfc-stringsconversion-specifier

Why don't use msg in printing instead of msg[pointer -1]?


It is printing correctly but I have confusion that whenever I write just msg, it gives me Your ?@ and whenever I write msg[option-1], it gives me full message of Your name is bilal. I am not understanding the cause of [option-1]. Why it is used and what is it's function?

#include <stdio.h>    
#define MAX_LEN 256

int main(){
  FILE * fp = fopen("file.txt","r");
  int option;
  char word[MAX_LEN];
  static const char * const msg[] = {
    "Name",
    "Date of Birth",
    "ID Card Number",
    "Phone Number",
    "Address",
    "Account", 
    "Fixing Year",
    "Amount" };
      for (option = 1; option <= sizeof(msg)/sizeof(char *); ++option)
      printf("%d. Your %s:\n", option, msg[option-1]);
  fclose(fp);
  return 0;
}

Solution

  • The conversion specifier %s is designed to output strings. It expects an argument of the type char *.

    The array msg is declared like

    static const char * const msg[] = {
    //...
    

    that is its elements have the type char *. The array itself used in expressions has the type char **. So it may be supplied to the conversion specifier %s.

    The valid range of indices to access elements of the array is [ 0, sizeod( msg ) / sizeof( char * ) ) while in the loop shown below the index variable is changed from [1, sizeof( msg ) / sizeod( char * ) + 1 ).

    That is in this loop

      for (option = 1; option <= sizeof(msg)/sizeof(char *); ++option)
    

    indices start fro 1. So to output correctly an element of the array you have to use the expression option - 1 as an index and the expression msg[option-1] has the required type char * that is expected by the conversion specifier of the call of prontf.

      printf("%d. Your %s:\n", option, msg[option-1]);
    

    That is the selected from the array string is outputted.