簡體   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接受字符串的地址,而在取消引用后不接受,而在使用指針的情況下則需要取消引用。

#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;
}

*使用時會崩潰,並且如果僅使用str則可以正常工作...

用於printf%s格式說明符用於打印字符串,並且需要一個char *參數,該參數指向以空字符結尾的字符數組的第一個元素。 %d格式說明符用於以十進制格式顯示整數,並且期望為int

由於str是一個數組,因此在表達式中使用時,它將衰減為指向其第一個元素的指針。 因此,表達式中的str類型為char * ,與%s期望的類型匹配。

*str對於%s無效,因為它的類型為char並且具有數組中第一個字符的值。 printf的給定參數使用錯誤的格式說明符會調用未定義的行為

*p%d有效,因為p類型為int * ,這意味着*p類型為int ,與%d期望的匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM