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

问题描述 投票:-2回答:2

我编写的以下代码显示了奇怪的行为,取决于我是否在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);
}
c pointers scanf
2个回答
1
投票

您的问题是由于当您插入一个整数时,您输入一个换行符,该换行符被视为一个字符并插入到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;
}

工作会议:

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 - 它是非标准的,有些编译器不支持它。另外,你不要从中调用任何功能。


1
投票

使用%p打印指针值。

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);

如果你注释掉你提到的两行,n将是未初始化的。

Demo

© www.soinside.com 2019 - 2024. All rights reserved.