我编写的以下代码显示了奇怪的行为,具体取决于我是否在 main()
中“注释”第三行和第四行。功能。如果我“评论”printf
和scanf
语句,代码的行为符合预期,否则会产生意外的结果/输出。
请帮助我了解我缺少什么。基本上,我只是一个试图理解指针的 C 新手。
#include <stdio.h>
#include <conio.h>
void main() {
int n, *ptr1;
char ch, *ptr2;
printf("Enter an integer\n");
scanf("%d", &n);
printf("Enter any single alphabetic character\n");
scanf("%c", &ch);
ptr1 = &n;
ptr2 = &ch;
printf("\nThe integer is %d and its pointer is %d in the address %d\n", n, *ptr1, ptr1);
printf("\nThe character is %c and its pointer is %c in the address %d\n", ch, *ptr2, ptr2);
}
最佳答案
您的问题是由于当您插入整数时,您输入了一个换行符,该换行符被视为字符并插入到 ch 变量中。将前导空格添加到第二个 scanf 调用中以忽略前一个换行符。
#include<stdio.h>
int main()
{
int n,*ptr1;
char ch,*ptr2;
printf("Enter an integer\n");
scanf("%d",&n);
printf("Enter any single alphabetic character\n");
scanf(" %c",&ch);// <- space added
ptr1=&n;
ptr2=&ch;
printf("\nThe integer is %d and its pointer is %d in the address %p\n", n, *ptr1, (void*) ptr1);
printf("\nThe character is %c and its pointer is %c in the address %p\n",ch, *ptr2, (void*) ptr2);
return 0;
}
工作 session :
Enter an integer
6
Enter any single alphabetic character
b
The integer is 6 and its pointer is 6 in the address 0x22cc84
The character is b and its pointer is b in the address 0x22cc83
PS。不要使用 conio.h
- 它是非标准的,并且某些编译器不支持它。另外,您不会从中调用任何函数。
关于c - 使用指针时 C 中的奇怪代码行为,其中注释代码的某个不相关部分会影响输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55075181/