简体   繁体   中英

c programming, why printf does not working?

#include<stdio.h>

int main(void)  {
  char op;
  int arr[3];
  printf("input ");
  scanf("%d %c %d", arr,&op,arr+1);  
  arr[3]=arr[0]-arr[1]; //here
  printf("[%c] %d\n", op, arr[3]); 
  return 0;
}

arr[3]=arr[0]-arr 1 ; printf("[%c] %d\\n", op, arr[3]);

why does not print %c ?

在此处输入图片说明

This:

arr[3]=arr[0]-arr[1];
printf("[%c] %d\n", op, arr[3]);

should be

arr[2] = arr[0] - arr[1];
printf("[%c],  %d\n", op, arr[2]);

because array indices start from 0 and end at length - 1. Using arr[3] leads to Undefined Behavior as you access memory locations that you shouldn't.

In your case, arr[3] might've been op . So in the examples you've given, op 's value is changed to 2 and 1 respectively, and thus, the printf tries to print an unprintable control character and the terminal displays a space as these control characters are unprintable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM