c - 使用指针时 C 中的奇怪代码行为,其中注释代码的某个不相关部分会影响输出

标签 c pointers scanf

我编写的以下代码显示了奇怪的行为,具体取决于我是否在 main() 中“注释”第三行和第四行。功能。如果我“评论”printfscanf语句,代码的行为符合预期,否则会产生意外的结果/输出。 请帮助我了解我缺少什么。基本上,我只是一个试图理解指针的 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/

相关文章:

c - 在 C 中使用 printf 添加

c - 我是否需要在 BinaryTree 中释放根或数据?

c - 用这个简单的代码发现错误?

c - 信息 C5012 : loop not parallelized due to reason ‘1007’

c - 设置结构的指针成员,从指针到结构的指针

c - 使用 *varname 定义字符串时,Sprintf 失败,传递给 loadrunner 中函数的参数无效

c++ - 将数字传递给成员函数导致程序崩溃

c - printf 不产生输入值

c - 使用 fscanf 将文件中的单词存储在数组中

c - 使用 fscanf() 用文件信息填充 C 中的链表,它不是在读取文件的第一行吗?