简体   繁体   English

printf以不同的方式表现……并采用地址和值……字符串的地址和指针的地址,仅在解引用之后

[英]printf is behaving in different ways…and taking address as well as value…address of string and for a pointer only after dereferencing

printf is taking address of string and not taking after dereferencing, whereas in case of pointer it is required to dereference. printf接受字符串的地址,而在取消引用后不接受,而在使用指针的情况下则需要取消引用。

#include <stdio.h>
#include<stdio.h>

int main()
{
    char str[100];
    int i;
    int j=0;
    int *p;

    p=&j;
    scanf("%s",str);
    for(i=0;str[i];i++)
    {
        if((str[i]>='A') && (str[i]<='Z'))
        {
            str[i]=str[i]+('a'-'A');
        }
        else
        {
            str[i]=str[i]-('a'-'A');
        }
    }
    printf("%s",str);   //it should have been printf("%s",*str); here we are  passing address
    printf("%d\n",j);
    printf("%d",*p);    //here we are passing evact value;

    return 0;
}

when used with * it crashes and if only str is used it works fine... *使用时会崩溃,并且如果仅使用str则可以正常工作...

The %s format specifier to printf is used to print a string and expects a char * argument which points to the first element of a null-terminated character array. 用于printf%s格式说明符用于打印字符串,并且需要一个char *参数,该参数指向以空字符结尾的字符数组的第一个元素。 The %d format specifier is used to print an integer in decimal format and expects an int . %d格式说明符用于以十进制格式显示整数,并且期望为int

Since str is an array, when used in an expression it decays into a pointer to its first element. 由于str是一个数组,因此在表达式中使用时,它将衰减为指向其第一个元素的指针。 So str in an expression has type char * , which matches what %s expects. 因此,表达式中的str类型为char * ,与%s期望的类型匹配。

*str is not valid for %s because that has type char and has a value of the first character in an array. *str对于%s无效,因为它的类型为char并且具有数组中第一个字符的值。 Using the wrong format specifier for a given argument to printf invokes undefined behavior . printf的给定参数使用错误的格式说明符会调用未定义的行为

*p is valid for %d because p has type int * , meaning that *p has type int , which matches what %d expects. *p%d有效,因为p类型为int * ,这意味着*p类型为int ,与%d期望的匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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