-3

In this PROGRAM 1 i am not getting the expected output.

// PROGRAM 1
#include <stdio.h>

int main () {
  char str1, str2;

  printf("Enter char1: \n");
  scanf("%c", str1);

  printf("Enter char2: \n");
  scanf("%c", str2);

  printf("Entered char1: %c\n", str1);
  printf("Entered char2:%c\n", str2);

  return(0);
}

In this program i am getting expected output. So pls tell me the reason why not for PROGRAM 1

//PROGRAM 2
#include <stdio.h>

int main () {
  char str1[5], str2[5];

  printf("Enter name: \n");
  scanf("%s", str1);

  printf("Enter your website name: \n");
  scanf("%s", str2);

  printf("Entered Name: %s\n", str1);
  printf("Entered Website:%s\n", str2);

  return(0);
}
Abdulvakaf K
  • 606
  • 1
  • 7
  • 16

2 Answers2

3

scanf needs a pointer as argument. So you should change the scanfs in your first program to :

scanf("%c", &str1);

and

scanf("%c", &str2);

in order to pass the addresses of your variables.


The reason why the second program works is that str1 and str2 in this case are arrays, so when you pass their names as arguments to scanf, you actually pass their addresses. This happens because array names decay to pointers. You can also refer to this answer for more details.

Marievi
  • 4,951
  • 1
  • 16
  • 33
1

In first program, %c format specifier print only one character. So, if you want to print only one character then use %c format specifier.

Also, If you scan character type then use &. like scanf("%c",&str2);

In second program, %s format specifier print string. So, if you want to print string then use %s format specifier.

%s no need to & because string buffers are already represented as addresses.

msc
  • 33,420
  • 29
  • 119
  • 214